Java generics - Does Java require support for locally defined types?

I hope to find Java generation experts here. Say you have some kind of typed class:

public interface SomeClass<T> {
    void doSomething(final T t);
}

There is also a function that provides you with an instance Tfor an instance SomeClass<T>:

public static class Retriever {
    public <T> T get(final SomeClass<T> c) {
        return null; // actual implementation left out
    }
}

Now let's say you have a collection SomeClass<?>and a retriever:

final List<SomeClass<?>> myClasses   = null; // actual implementation left out
final Retriever          myRetriever = null; // actual implementation left out

We cannot do the following:

for (final SomeClass<?> myClass : myClasses) {
    myClass.doSomething(myRetriever.get(myClass));
}

Now my question is: do I need Java support for local type determination? Sort of:

<T> for (final SomeClass<T> myClass : myClasses) {
    myClass.doSomething(myRetriever.get(myClass));
}

Here the type is Tbound to a for loop. We define Tto get rid of the wildcard ?. It. The introduction Tshould allow us to write down the desired cycle cycle, as indicated above.

FWIW, . ? T.

for (final SomeClass<?> myClass : myClasses) {
    workAround(myRetriever, myClass);
}

public static <T> void workAround(final Retriever myRetriever, final SomeClass<T> myClass) {
    myClass.doSomething(myRetriever.get(myClass));
}

?

+4
1

: Java ?

. , .. , T for, , . :

<T> void method(List<SomeClass<T> myClasses) {
    for (final SomeClass<T> myClass : myClasses) {
        myClass.doSomething(myRetriever.get(myClass));
    }
}
+3

Source: https://habr.com/ru/post/1613705/


All Articles