Martin Ždila
Martin Ždila

Reputation: 3219

How to create java.lang.Class with type parameter that is also typed?

What to put on place of ??? in the following code so it would work?

import java.util.List;

public class Generic {

    private static class Foo<T> {
        Foo(Class<T> clazz) {
            assert clazz != null;
        }
    }

    public static void main(String[] args) {
        Class<List<String>> x = ???;
        Foo<List<String>> t = new Foo<List<String>>(x);
    }

}

Upvotes: 4

Views: 369

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533492

At runtime, all List "classes" are equal as the generic type is erased

Class<List<String>> x = (Class<List<String>>) (Class) List.class;

Upvotes: 1

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

I would go for:

@SuppressWarnings("unchecked")
Class<List<String>> klass = (Class<List<String>>)((Class<?>) List.class);

And you do not need an instance of a the class for this type of cast.

Upvotes: 6

Related Questions