The question title is probably confusing, so I will do my best to explain what I am after.
Goal
Use Java reflection to instantiate and set private members of a class (Code Block One). The class in question does not have a public constructor, and the private constructor is empty (Code Block Two). Two maps will be used. One map will hold the fields and the other will hold the objects of those fields (Code Block Three).
Issue
I have a List
that is set with ArrayList
in the class. When using the initialization code for the list, it does not get ArrayList
as the class. I can expand the class that creates the objects from reflection, but I need it to be able to detect what kind of list is being used.
Desired Solution
A way to get what implementation of List
is set to the class member and call off to a function that handles that creation of the object.
Code Block One
final Constructor objDef = clazz.getDeclaredConstructor();
objDef.setAccessible(true);
return clazz.cast(objDef.newInstance());
Code Block Two
private List<OfClass2> listOfObjects = new ArrayList<>();
private OfClass1() {}
Code Block Three
for(Field field : fields) //fields is the return of getClass().getDeclaredFields()
{
final Class<?> c = field.getType();
final Object obj = ReflectCreator.create(c); //Calls off to Code Block One
fieldMap.put(field.getName(), field);
objectMap.put(field, obj);
}
Aucun commentaire:
Enregistrer un commentaire