dimanche 23 juillet 2017

Dynamically casting object type to specific class type using reflection

I have many Cog classes are all similar, and I need to add them to parameterized lists of type Cog based on the class path.Cog_1, Cog_2,..., Cog_N. Is there anyway to use reflection to cast an Object type to specific Cog class if I have the path?

main(){
List<Cog> CogList = LIsts.newArrayList();
List<Cog_2> CogList_2 = LIsts.newArrayList();

CogList.add(createObject("path.to.Cog");
CogList_2.add(createObject("path.to.Cog_2");

Class<?> clazz3 = Class.forName("path.to.Cog_3");
//CogList_3.add(clazz3.cast(result);  Error add (Cog_3) to list cannot be applied to capture <?>
}

public Object createObject(String classPath){
Class<?> clazz = Class.forName(classPath);
Constructor<?> cons = clazz.getConstructor();
return  Object object = cons.newInstance();
}

I'd rather have not have to manually cast each object to type. It works, but but would add in a lot of boiler plate code.

if (result instanceof Cog_10){
 (Cog_10) clazz.cast(result)
}





Aucun commentaire:

Enregistrer un commentaire