How can I use a class object as a parameterized type?

So, Google had a lot of questions about getting a .classparameterized type, but I'm trying to go the other way.

I have a list of classes, and I need to create a map that uses Classas a key, and ArrayListobjects of type Class as a value. Something like that:

Class[] classes = getArrayOfClasses();
HashMap<Class, ArrayList<?>> map = new HashMap<Class, ArrayList<?>>();
for(Class c : classes) {
    map.put(c, new ArrayList<c>());    // here is where the problem is
}

The problem, of course, is that it needs a parameterized type, not a class. One possible solution is to simply use it map.put(c, new ArrayList<Object>()), but then I have to know the type and throw every object that I draw.

MyClass myObj = (MyClass) map.get(MyClass.class).get(0);

I also tried to make the initialization function as follows:

private <T> ArrayList<T> makeArrayList(Class<T> c) {
    return new ArrayList<T>();
}

, , , , ArrayList of Object, .

, , ArrayList ?

+4
2

, - Java ( ), .

, map.put(c, new ArrayList<c>());.

: :

public <T> getList(Class<T> key) {
    List<?> list = map.get(key);
    return (List<T>) list;
}

, , .

, , , .

public <T> getList(Class<T> key) {
    List<?> list = map.get(key);
    for(Object o : list){
        assert(key.isInstance(o));
    }
    return (List<T>) list;
}
+2

- :

new ArrayList();
new ArrayList<T>();
new ArrayList<String>();
new ArrayList<Integer>();

type ; . , , , , .

new ArrayList<Object>() new ArrayList<Integer>() new ArrayList<CompletelyBogusUnrelatedClass>(); , ArrayList<?>, .

, ArrayList, :

private static <T> ArrayList<T> makeArrayList() {
    return new ArrayList<T>();
}

(, ArrayList , , , ! , .)

+1

All Articles