If I have a class using generic type such as
public class Record<T> {
private T value;
public Record(T value) {
this.value = value;
}
}
it is pretty straight forward to type everything during design time, if I know all types that are used such as it is the case in this example:
// I type explicitly
String myStr = "A";
Integer myInt = 1;
ArrayList myList = new ArrayList();
Record rec1 = new Record<String>(myStr);
Record rec2 = new Record<Integer>(myInt);
Record rec3 = new Record<ArrayList>(myList);
What happens if I get a list of objects from “somewhere” where I don’t know the type? How do I assign the type:
// now let's assume that my values come from a list where I only know during runtime what type they have
ArrayList<Object> myObjectList = new ArrayList<Object>();
myObjectList.add(myStr);
myObjectList.add(myInt);
myObjectList.add(myList);
Object object = myObjectList.get(0);
// this fails - how do I do that?
new Record<object.getClass()>(object);
Java generics are not C++ Templates.
Java generics are a compile time feature, not a run time feature.
Here is a link to the Java generics Tutorial.
This can never work with Java:
You must either use polymorphism (say, each object implements a known interface) or RTTI (instanceof or Class.isAssignableFrom()).
You might do this:
or you might use the Builder pattern.