final T t = new T();
What will happen? Well you will get an compiler error like this: "Cannot instantiate the type T". Makes sense right? Remember Java uses type erasure .. and therefore this is just not valid. So what can we do? Well if you read my last entry you would come up with a solution like this maybe:
public static T createObject(final Class clazz) {
try {
return clazz.newInstance();
} catch (final InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Well this will work, but i want to share an alternative solution with you guys. Since we want to create a object we can use the design pattern called factory (in this example we will use an abstract factory). Let's see how this will work:
Here the abstract factory:
public abstract class AbstractFactory {
abstract T createObject();
}
And next the implementation:
public class UserFactory extends AbstractFactory {
@Override
User createNewTypedObject() {
return new User();
}
}
Not bad right? Well everything has drawbacks .. in this case if the user has some instance fields which need to be set, we would have initialiaze the object later. Which is critical. Anyway i liked the usage of this pattern in this use case .. let me know what you think ..
Keine Kommentare:
Kommentar veröffentlichen