Is this possible? I am creating a an object from a JSON string with this code:
String obj = new Gson().toJson(jsonArray.getJSONObject(i));
String className = getClassName(jsonArray.getJSONObject(i));
Class targetClass = null;
try {
targetClass = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//Create Object
Object data = new Gson().fromJson(obj, targetClass);
I then do some database stuff, get a return key value and I want to set that key on the bean object using its setId() setter, but I don’t want to have to cast the specific type of object to the generic object because that would require my repeating the exact same code many times just to cast the object.
key = contactsListDAO.manageDataObj(data, sql, true);
((PhoneNumber) data).setId(key);
Can I use some sort of if statement to check if the object contains an id property and then set the id on the generic object without having to cast?
reflection can do that but I think maybe here you should do something else.
Write a utility function
and then you can call it like so
no more conversion.
EDIT : if using “Object” is a constraint you can use reflection
Here is a working example I have, just copy-paste-run.
And the expected output is :