简体   繁体   中英

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?

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> , then you can write it as a return type:

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

You pass the type argument explicitly to 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 .

It seems you're using Guava's Sets . The method signature is the following:

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

As you can see newHashSet() takes a type parameter E . The result is HashSet<E> . E is inferred to be String , but you've specified the method to return 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> .

newHashSet will always return the type of its generic type argument. 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> .

You can simply pass it a Object instead by casting child explicitly to force the compiler to infer Object as the generic type instead:

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; the inference takes into account of the target type.

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

Using JDK's 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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