Passing / returning a class with a type parameter to a function

Suppose the following method (say, from language variables):

public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> type) {
    return null;
}

and this collection:

Set<?> objs = ...;

then the following code compiles and the generic data is correctly displayed

Iterable<String> a2 = Iterables.filter(objs, String.class);

(In Guava, this will return the iterability of all lines in objs.)

But now suppose the following class:

static class Abc<E> {
    E someField;
}

I have no idea how to call filterand get Iterable<Abc<?>>:

Iterable<Abc>    a3 = Iterables.filter(objs, Abc.class);
Iterable<Abc<?>> a4 = Iterables.filter(objs, Abc.class); // Compile error - Abc and Abc<?> are incompatible types
Iterable<Abc<?>> a5 = Iterables.filter(objs, Abc<?>.class); // Compile error
Iterable<Abc<?>> a6 = Iterables.<Abc<?>>filter(objs, Abc.class); // Compile error
Iterable<Abc<?>> a7 = (Iterable<Abc<?>>) Iterables.filter(objs, Abc.class); //  Compile error - inconvertible types
Iterable<Abc<?>> a8 = Iterables.filter(objs, new Abc<?>().getClass()); // Compile error
Iterable<Abc<?>> a8a = Iterables.filter(objs, new Abc<Object>().getClass()); // Compile error

Only a3 compilation, but then I don't have a parameter on Abc, and thus the generic type check in the following code fails.

I know that type parameters are missing at runtime, so I'm not trying to write code like:

Iterable<Abc<String>> a9 = Iterables.filter(objs, Abc<String>.class); // Compile error

I just want to filter out all objects like Abc (like a3), but having a common parameter as a result. The only way to do this I found the following: stupid:

Iterable<Abc<?>> a10 = new HashSet<Abc<?>>();
for (Abc<?> a : Iterables.filter(objs, Abc.class)) {
    ((Set<Abc<?>>)a10).add(a);
}

Thank.

+5
2

. , , , .

Class<Abc<?>> . Abc s, .

@SuppressWarnings("unchecked")
public static Class<Abc<?>> ABC = (Class<Abc<?>>)(Object) Abc.class;
+6

..

public static <T> Iterable<Abc<T>> myFilter (Iterable<Abc<T>> myIterator) {
    Class<Abc<T>> myClass = null;
    Iterable<Abc<T>> a3 = Iterables.filter(myIterator, myClass); 
    return a3;
}

myFilter(). , .

0

All Articles