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