简体   繁体   中英

Java: Return unknown generic type in method

The method

Filter<T,U> connect(final Filter<T,U> filter) {
...
return filter
}

is in a class

class Pipe<T>

I get the Error "Cannot resolve U". The idea is to just generically return the same filter with the same two types without knowing the U type. How do i do that?

The goal is to be able to chain without providing type parameters, when they are not necessary because they do not get modified:

(new Pipe<Integer>).connect(new Filter<>(...)).connect(new Pipe<>)...

The second Pipe after the Filter in the above expamle shall implicitly be of the generic type Integer.

It looks like you are trying to make your method generic . To do this simply add generic type U to its signature right before return type:

<U> Filter<T,U> connect(final Filter<T,U> filter) {
    ...
    return filter
}

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