public <T> T genericMethod(Class<T> tClass)throws InstantiationException ,
IllegalAccessException{
T instance = tClass.newInstance();
return instance;
}
Object obj = genericMethod(Class.forName("com.test.YourClass"));
This is a typical code for java to use generic method return an instance of specific class. Instance of Class is pass as an variable and new instance is created by calling the constructor through reflection.
I am still confused by the mechanism of reflection and Class class. My question is, if the class information of YourClass will be erase from the Class instance, when calling the reflection method, why it can create an YourClass but not an object? Shouldn't an Object be created?
Aucun commentaire:
Enregistrer un commentaire