Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.7k users

Browse Categories

...