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);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…