mardi 30 juillet 2019

how to initialize class and specify generic type of class by reflection

1, The custom class definition:

public class MyClass<T> {

    private T property;

    public MyClass() {
    }

    public MyClass(T property) {
        this.property = property;
    }


}


2, normal initialization as following is worked:

MyClass<String> stringMyClass = new MyClass<>();
stringMyClass.setProperty("hello");
System.out.println("stringMyClass:" + stringMyClass.getProperty());


Requirments:

The requirments is to initialize instance by reflection. The T will be specified dynamically. Such as:

Constructor<MyClass> con = MyClass.class.getDeclaredConstructor(String.class);
con.setAccessible(true);
MyClass hello = con.newInstance("hello");
System.out.println("property:" + hello.getProperty());

but reflection code above is not working, error message as following:

Exception in thread "main" java.lang.NoSuchMethodException: test.mytest.MyClass.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at test.mytest.Main.main(Main.java:8)

How to initialize it by reflection ?





Aucun commentaire:

Enregistrer un commentaire