简体   繁体   English

如何强制使用静态泛型方法的返回类型?

[英]How do I force a static generic method's return type?

Having a class hierarchy: 有一个类层次结构:

String child = null;
Object parent = child;

How do I force Sets.newHashSet(E...) to return a Set<Object> while passing String arguments? 如何在传递String参数时强制Sets.newHashSet(E...)返回Set<Object>

You can specify generic return type with: 您可以指定泛型返回类型:

Sets.<Object>newHashSet(child);

Maybe it would be OK for you to return Set<? extends Object> 也许你可以返回Set<? extends Object> Set<? extends Object> , then you can write it as a return type: Set<? extends Object> ,然后你可以把它写成一个返回类型:

public Set<? extends Object> myMethod() {
    return Sets.newHashSet(child);
}

You pass the type argument explicitly to newHashSet : 您将type参数显式传递给newHashSet

Sets.<Object>newHashSet(child);

If the type argument isn't passed explicitly the type is inferred and in this case it's inferred to the wrong type, presumably String . 如果未明确传递type参数,则推断出类型,在这种情况下,它推断为错误类型,可能是String

It seems you're using Guava's Sets . 看来你正在使用Guava的套装 The method signature is the following: 方法签名如下:

public static <E> HashSet<E> newHashSet()

As you can see newHashSet() takes a type parameter E . 如您所见, newHashSet()采用类型参数E The result is HashSet<E> . 结果是HashSet<E> E is inferred to be String , but you've specified the method to return Set<Object> . E被推断为String ,但您已指定返回Set<Object> The solution is to either help the compiler or loosen the restriction in the return type to Set<? extends Object> 解决方案是帮助编译器还是将返回类型中的限制放宽到Set<? extends Object> Set<? extends Object> . Set<? extends Object>

newHashSet will always return the type of its generic type argument. newHashSet将始终返回其泛型类型参数的类型。 Since the type of child is String the compiler will infer the generic type to be String and the function will return a HashSet<String> . 由于child类型是String ,编译器会将泛型类型推断为String ,函数将返回HashSet<String>

You can simply pass it a Object instead by casting child explicitly to force the compiler to infer Object as the generic type instead: 你可以简单地传递一个Object的,而不是铸造child明确强制编译器来推断Object作为泛型类型来代替:

Sets.newHashSet((Object) child);

Alternatively you can force the generic type and the compiler can now see that the cast is trivial: 或者,您可以强制使用泛型类型,编译器现在可以看到强制转换:

Sets.<Object>newHashSet(child);

In Java 8, this compiles just fine; 在Java 8中,这个编译得很好; the inference takes into account of the target type. 推理考虑了目标类型。

public Set<Object> myMethod() {
    return Sets.newHashSet(child);
}

Using JDK's API: 使用JDK的API:

public Set<Object> myMethod() {
    return Collections.singleton(child); // Works too
}

In Java 5, 6, 7 the inference on this call is done on argument types alone. 在Java 5,6,7中,仅对参数类型进行了对此调用的推断。

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

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