vendredi 9 novembre 2018

Java reflection get constructor from class name failed

I've this code snippet:

class You{
    public You(String s){}
}

public static void main(String[] args)  throws NoSuchMethodException {
    Constructor[] constructors = You.class.getConstructors();
    for(Constructor constructor: constructors){
        Class[] parameterTypes = constructor.getParameterTypes();
        for(Class c: parameterTypes){
            System.out.println(c.getName());//print java.lang.String
        }
    }
    Constructor constructor =
            You.class.getConstructor(String.class);//NoSuchMethodException?
}

This is quite old, when I print the constructors, it has one ctor with "java.lang.String" as parameter. But when I tried to "You.class.getConstructor" it says no ctor with "String.class" as parameter.

I'm using java1.8 on mac. Would you help to explain and how to fix?

Thanks a lot.





Aucun commentaire:

Enregistrer un commentaire