开发者

how to specify the genric type in runtime

I'm having a arraylis开发者_如何学JAVAt which I need to specify the type in runtime.

ArrayList<String> alist = new ArrayList<String>();

I need to specify the type "String" at runtime. how can I do that. It should not be static.


Thats no possible due to type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method.

It's only available during compile time, to check types.

EDIT: As a workaround to your problem you could use ArrayList<Object> this would allow you to add any types to the ArrayList. In this case you could check types using instanceof and cast to concrete types.


You mean you want to parameterize the type used to create the ArrayList?

public <T> List<T> interestingMethod(Class<T> type) {
    List<T> aList = new ArrayList<T>();
    // do something interesting...
    return aList;
}

Passing the type argument is only needed for type inference and I find this pattern a kludge, but it's the only way with Java.

As the everyone else will point out, we don't have runtime type information with generics because of type erasure.


The generic type parameter is not compiled into the bytecode, therefore it is not available at runtime. An ArrayList<String> is simply an ArrayList at runtime. The closest thing you can achieve, is to add runtime checks yourself. For example, Collections class provides a decorator that does exactly this:

List l = Collections.checkedList(new ArrayList<String>(), String.class);
l.add("Jave uses erasure");
l.add(14);

If the list was created simply as ArrayList<String>, the two additions would succeed at runtime. With the wrapper implementation however, every item addition is validated, so the second call will cause a ClassCastException.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜