I have an object initialized like :
Object obj = new Object(){
final String type = "java.lang.Integer";
final Object value = 6;
};
I want to recreate this object as :
Integer i = 6;
Is there any way I can get the type
field of obj
object and create a new instance using reflection and feed the value in it?
EDIT : Upon extending this question, I find that if I have the object stored in file and retrieve it from file using Jackson using this :
Reader reader = new Reader();
MyClass[] instances = reader.readValue(fileName);
And MyClass
is defined as :
class MyClass{
List<Object> fields;
.
.
.
}
Now I am iterating the fields
and converting them into proper objects using the code :
public static Class<?> getTypeForObject(Object field) {
Field returnType = null;
try {
returnType = field.getClass().getDeclaredField("type");
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return returnType.getType();
}
public static Object getValueForObject(Object field) {
Object obj = null;
try {
obj = field.getClass().getDeclaredField("value").get(field);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return obj;
}
But when I watch the expression field.getClass()
, it gives me LinkedHashMap
as its class. I am confused why and if it that Object is internally treated as Map
what options am I left with if I want to do it with reflection without using an concrete data structures so that everything is generalized.