Is there a (better) way to dynamically create Objects?
Right now I’m using a simple ‘factory pattern’ solution as following:
String classType = generalObject.getClass().toString();
if(classType.equals("class be.testApp.UserObject")) {
return UserObject.fromByteArray(data);
//return new UserObject();
}
else if(classType.equals("class.be.testApp.NewsObject")) {
return NewsObject.fromByteArray(data);
//return new NewsObject();
}
This code is not a factory pattern and no object is created. You evaluate the class name and call a static method on a class.
Now it looks like you have an object (
generalObject) and want to create a new instance of the very same type. If all possible types have a public default constructor (convention!), then you can use this to create a new instance based on the given object:(but maybe I still didn’t get your idea…)