May be many of you have several times wanted to do this. Right now I am trying to do it but stuck.
Say, I have a method like this:
private Object getList(String nameofType) {
return new ArrayList<Type>();
/**e.g. It returns ArrayList<java.lang.Double> if nameofType is "java.lang.Double",
/*ArrayList<java.io.File> if nameofType is "java.io.File"**/
}
How can I init an ArrayList like this?
The closest thing to what you want to do, might be this:
private List getList(String nameofType) {
List list = null;
try {
Class clazz = Class.forName(nameofType); //must be fully qualified, example: "java.lang.Integer"
list = Collections.checkedList(new ArrayList(), clazz);
} catch (ClassNotFoundException e) {
// log exception, etc.
}
return list;
}
This will return an effectively type-checked list, that will throw an exception if you try to insert an object of different type than specified.
You can check it four yourself:
List list = getList("java.lang.Integer");
System.out.println("Inserting Integer");
list.add(new Integer(1));
System.out.println("List: "+ list);
System.out.println("Inserting Long");
list.add(new Long(1));
System.out.println("List: "+ list);
Output:
Inserting Integer
List: [1]
Inserting Long
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Long element into collection with element type class java.lang.Integer
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments