Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

How can I achieve this?

public class GenericClass<T>

{

    public Type getMyType()

    {

        //How do I return the type of T?

    }

}

Everything I have tried so far always returns the type Object rather than the specific type used.

1 Answer

0 votes
by (46k points)

Try this:

private Class<T> persistentClass;

public Constructor() {

    this.persistentClass = (Class<T>) ((ParameterizedType) getClass()

                            .getGenericSuperclass()).getActualTypeArguments()[0];

 }

To learn more about it click here.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...