2

我正在使用List.class,因为List<String>.class是错误的。是否有获取参数化类的类的语法?

代码:

import java.util.List;
import org.apache.camel.Message;
...
    Message m = exchange.getIn();
    List<String> serviceIds = null;
    serviceIds = m.getHeader("serviceId", List.class);

我当然更愿意:

    serviceIds = m.getHeader("serviceId", List<String>.class);

如果标题中包含非字符串的列表,则确保 getHeader 将返回 null。

4

2 回答 2

7

你不能给它一个类 of List<String>,因为没有这样的类:<String>编译器在称为类型擦除的过程中删除了类型 of ,给你留下了 pure List

于 2012-09-21T14:48:22.197 回答
3

I'm not entirely sure I understand your question, but if you have a List parameterized with some class, eg:

List<Cat> myCats = new ArrayList<Cat>();

And you have some API method that you want to call:

public static void doSomething(Class<T> clazz);

And you're looking to provide that method with Cat.class, there is unfortunately no way to determine (at runtime) the parameterized class that is being contained in the List. This information is erased at runtime.

I believe your question may be a duplicate of this one, but don't hesitate to correct me if I'm mistaken:

How to get the generic type at runtime?

于 2012-09-21T14:50:20.173 回答