[英]How to return class type of a generic class with generic?
假设我有这样的界面;
public interface Validator<T> {
Class<T> type();
}
如果我想用一个对象实现这个接口,没有任何问题;
public OrderValidator implements Validator<Order>{
Class<Order> type(){
return Order.class;
}
}
但是,如果我将Collection作为泛型类型传递,我就无法实现此接口;
public CollectionValidator implements Validator<Collection<Item>>{
Class<Collection<Item>> type(){
//how can I implement this method to return type of Collection<Item> ?
}
}
如何实现type()
方法返回Collection< Item>
类型?
Collection< Item>.class
不起作用。
如果你只想让它编译,那么试试:
public interface Validator<T> {
Class<T> type();
}
public static class CollectionValidator<Item> implements Validator<Collection<Item>>{
@SuppressWarnings("unchecked")
public Class<Collection<Item>> type() {
return (Class<Collection<Item>>) (Class<?>) Collection.class;
}
}
试试这样:
接口:
public interface MyInterface<T> {
Class<?> type();
}
执行:
public class MyClass implements MyInterface<Object>{
@Override
public Class<?> type() {
//some collection to test
List<String> lst = new LinkedList<>();
return lst.getClass();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.