Alex Rivera | Logout

How to do `MyClass<String>.class` in Java?

Asked 2011-03-05T22:17:53.287
17

How can call public <T> T doit(Class<T> clazz); using MyClass<String>.class as clazz where I can not instantiate or extend MyClass.

EDIT: 'David Winslow' and 'bmargulies' responses are correct (MyClass<String>) doit(MyClass.class); works for the original question BUT surprisingly when the method returns say MyClass<T> instead of T casting will not compile any more.

Edit: I have replaced List with MyClass and added the condition to my original question.

Edit
Report

1 Answer

1

Since after your update your question does not appear to be an exact duplicate:

You would need to call getClass() on an instance of MyClass. Better have a dummy static final instance somewhere:

public static final MyClass INSTANCE = new MyClass();
...
return (Class<MyClass<String>>) instance.getClass();
answered 2011-03-05T22:20:52.553

Your Answer