Problème avec Class.forName et newInstance : comment invoquer des méthodes ?

thierrylafleur Messages postés 10 Date d'inscription mercredi 5 avril 2006 Statut Membre Dernière intervention 27 octobre 2006 - 29 juin 2006 à 10:57
thierrylafleur Messages postés 10 Date d'inscription mercredi 5 avril 2006 Statut Membre Dernière intervention 27 octobre 2006 - 29 juin 2006 à 13:45
Salut,

Mon problème est un peu compliqué (pour moi évidemment, peut-être pas pour vous) donc j'ai essayé de simplifier la situation
J'ai la classe suivante :
public class Hello
{
public Hello()
{}

public String getHello()
{
return "Hello";
}
}
et une autre classe :
public class Toto
{
public Toto()
{}
public String getString(String nomClasse)
{
Class clHello = Class.forName(nomClasse);
Object o = clHello.newInstance();
String s = // C'est là que j'aimerais invoquer la méthode getHello() de la class Hello
}
}

Après si je voudrais faire ça ailleurs :
Toto toto = new Toto()
String s = toto.getString("Hello");

Voilà, je ne sais pas comment faire.
Désolé, je suis débutant dans le Java, la solution est peut-être toute con mais je vois pas.
Merci pour vos réponses.

2 réponses

Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
29 juin 2006 à 12:58
Salut,


voici un petit test qui fonctionne (pour info jdk 1.5) :


import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;


public class TestReflect {


    public static void main(String[] args) {

        TestReflect tr = new TestReflect();

        System.out.print(tr.getStringVoidMethod("Hello", "getHello"));

        System.out.print(tr.setString1Param("Hello",  "getHello", " world !!!"));

        //System.out.println(tr.getStringVoidMethod("Hello", "getHello"));

    }

   

     public String getStringVoidMethod(String nomClasse, String nomMethode){

         Class c = null;

        try {

            c = Class.forName(nomClasse);

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

            return "";

        }

        Object o = null;

         try {

            o = c.newInstance();

        } catch (InstantiationException e) {

            e.printStackTrace();

            return "";

        } catch (IllegalAccessException e) {

            e.printStackTrace();

            return "";

        }

        Method m = null;

         try {

            m = c.getMethod(nomMethode, new Class[]{});

        } catch (SecurityException e) {

            e.printStackTrace();

            return "";

        } catch (NoSuchMethodException e) {

            e.printStackTrace();

            return "";

        }

        Object ret = null;

        try {

            ret = m.invoke(o, new Object[]{});

        } catch (IllegalArgumentException e) {

            e.printStackTrace();

            return "";

        } catch (IllegalAccessException e) {

            e.printStackTrace();

            e.printStackTrace();

            return "";

        } catch (InvocationTargetException e) {

            e.printStackTrace();

            e.printStackTrace();

            return "";

        }

        if(ret == null)return "";

       

        return ret.toString();

     }

     

     

     public String setString1Param(String nomClasse, String nomMethode, String argument){

         Class c = null;

        try {

            c = Class.forName(nomClasse);

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

            return "";

        }

        Object o = null;

         try {

            o = c.newInstance();

        } catch (InstantiationException e) {

            e.printStackTrace();

            return "";

        } catch (IllegalAccessException e) {

            e.printStackTrace();

            return "";

        }

        Method m = null;

         try {

            m = c.getMethod(nomMethode, new Class[]{String.class});

        } catch (SecurityException e) {

            e.printStackTrace();

            return "";

        } catch (NoSuchMethodException e) {

            e.printStackTrace();

            return "";

        }

        Object ret = null;

        try {

            ret = m.invoke(o, new Object[]{argument});

        } catch (IllegalArgumentException e) {

            e.printStackTrace();

            return "";

        } catch (IllegalAccessException e) {

            e.printStackTrace();

            return "";

        } catch (InvocationTargetException e) {

            e.printStackTrace();

            return "";

        }

       

        if(ret == null)return "";

       

        return ret.toString();

     }


}


class Hello {

    public Hello() {

    }

   

    public String getHello() {

        return "Hello";

    }

   

    public String getHello(String hello) {

        return hello;

    }


}


J'ai volontairement ommis les commentaire vu que sur les how to de sun
il y a un tutorial complet sur les mécanismes de reflexion. donc si tu veux plus d'info vas dessus.

------------------------------------
"On n'est pas au resto : ici on ne fait pas dans les plats tout cuits ..."

WORA
0
thierrylafleur Messages postés 10 Date d'inscription mercredi 5 avril 2006 Statut Membre Dernière intervention 27 octobre 2006
29 juin 2006 à 13:45
Excellent !
Merci bien, c'est tout ce que je voulais.
0
Rejoignez-nous