繁体   English   中英

如何使用泛型返回泛型类的类类型?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM