简体   繁体   English

Java:一般返回由参数指定的类型集

[英]Java: generically return a typed Set specified by parameter

I want to have a method that generically creates a list of a specified interface.我想要一个方法来创建一个指定接口的列表。 I can't seem to get it so that I don't have to cast or that I loose my type-safety.我似乎无法得到它,因此我不必强制转换或失去类型安全性。

This version requires casting of the Set and produces unsafe type cast warnings:此版本需要转换 Set 并产生不安全的类型转换警告:

public static Set<? extends Setting> getSettings(Class<? extends Setting> className){
    Set<? extends Setting> result = new HashSet<>();
    try {
        Setting settingsObject = className.getDeclaredConstructor().newInstance();
        // do something with it and populate result-set
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}   


public static void main(String[] args)  {
    Set<LiabilitySetting> liabilitySettings = (Set<LiabilitySetting>) getSettings(LiabilitySetting.class);
    for (LiabilitySetting s: liabilitySettings) {
        s.doSomething();
    }

}

while with this version I need to cast the elements of the set before using them而在这个版本中,我需要在使用它们之前投射集合的元素

public static Set<Setting> getSettings(Class<? extends Setting> className){
    Set<Setting> result = new HashSet<>();
    try {
        Setting settingsObject = className.getDeclaredConstructor().newInstance();
        // do something with it and populate result-set
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}   


public static void main(String[] args)  {
    Set<Setting> liabilitySettings = getSettings(LiabilitySetting.class);
    for (Setting s: liabilitySettings) {
        ((LiabilitySetting) s).doSomething();;
    }

}

I feel there is a way of writing my method without loosing type-safe and without having to cast.我觉得有一种方法可以在不丢失类型安全且无需强制转换的情况下编写我的方法。 Any ideas?有任何想法吗?

Use a bounded type parameter instead.改用有界类型参数。

public static <T extends Setting> Set<T> getSettings(Class<T> className) {

The wildcard ?通配符? tells the compiler that it's some subclass of Setting (or Setting itself), but the compiler doesn't know whether the ?告诉编译器它是Setting (或Setting本身)的某个子类,但编译器不知道? in the Class is the same as the ?Class是一样的? in the Set .Set

When you bind it to a type parameter, the compiler still knows that T is a subclass of Setting or Setting , but now it knows that the Set and the Class have the same type, removing the need for a cast.当你将它绑定到一个类型参数时,编译器仍然知道TSettingSetting的子类,但现在它知道SetClass具有相同的类型,不需要强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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