0

Here's a simplified method I have to implement:

class Sample<T> {
    Class<List<T>> getType() {

    }
}

So the solution to it could be:

class Sample<T> {

    final Class<List<T>> type;

    Sample(Class<List<T>> type) {
        this.type = type;
    }

    Class<List<T>> getType() {
        return type;
    }

    static void test() {
        @SuppressWarnings("unchecked")
        Class<List<Integer>> clazz = (Class<List<Integer>>) (Class<?>) List.class;
        Sample<Integer> sample = new Sample<>(clazz);
    }
}

Is there a way to avoid the warning when instantiating clazz?

Or even better - to avoid passing it in constructor and just get the desired result based on the class type?

Thanks!

Janek
  • 1,441
  • 2
  • 19
  • 28
  • 1
    Possible duplicate of [Get type of a generic parameter in Java with reflection](https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection) – Logan Jun 07 '18 at 02:09
  • 1
    Honestly this code looks broken. I think there's something wrong with the way you're designing it. – markspace Jun 07 '18 at 02:14
  • It is not clear what you are trying to accomplish there. If you want to check the class type, you should look for the "instanceof" in Java documentation. – Victor Havin Jun 07 '18 at 02:21
  • There's no way to avoid that warning, aside from not doing this at all. There's not really any such thing as a `Class>`. – Radiodef Jun 07 '18 at 02:22
  • You should probably store `Class` instead, if `List` is always going to be the same. – Sean Van Gorder Jun 08 '18 at 18:51

0 Answers0