get a class instance of generics type T

0 votes
I have a generics class, Moo<T>. In a method of Moo,  get the class instance of type T, but I just can't call T.class.

What is the preferred way to get around it using T.class?
May 29, 2018 in Java by sharth
• 3,370 points
5,270 views

1 answer to this question.

0 votes

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java.

A  solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

class Moo<T> {
    final Class<T> typeParameterClass;

    public Moo(Class<T> typeParameterClass) {
        this.typeParameterClass = typeParameterClass;
    }

    public void bar() {
        // you can access the typeParameterClass here and do whatever you like
    }
}
answered May 29, 2018 by Parth
• 4,640 points

Related Questions In Java

0 votes
2 answers

How can I get the filenames of all files in a folder which may or may not contain duplicates

List<String> results = new ArrayList<String>(); File[] files = ...READ MORE

answered Sep 12, 2018 in Java by Sushmita
• 6,920 points
1,919 views
0 votes
2 answers

Get all the permutations of a string in Java

You could use recursion to do this.  Try ...READ MORE

answered Aug 21, 2019 in Java by Sirajul
• 59,230 points
2,254 views
0 votes
1 answer

Use of Static Keyword in a Class

It means that there is only one ...READ MORE

answered May 29, 2018 in Java by Rishabh
• 3,620 points
663 views
0 votes
2 answers

How do i create generic array in Java

as first tip you cannot assign value ...READ MORE

answered Feb 13, 2020 in Java by sama
17,228 views
0 votes
1 answer

How can I make the return type of a method generic?

First of all, define callFriend: public <T extends ...READ MORE

answered May 19, 2018 in Java by sharth
• 3,370 points
797 views
0 votes
2 answers

how can we Create instance for generic type in java

private static class SomeContainer<E> { ...READ MORE

answered Aug 27, 2018 in Java by Sushmita
• 6,920 points
26,823 views
0 votes
1 answer

How to get the Generic type of class at run time?

public class GenericClass<T> { ...READ MORE

answered Jul 2, 2018 in Java by Akrati
• 3,190 points
830 views
0 votes
2 answers

How can I sort values of a Map in Java using its key

Assuming TreeMap is not good for you ...READ MORE

answered Oct 10, 2018 in Java by Sushmita
• 6,920 points
1,207 views
0 votes
2 answers

One line initialization of an ArrayList object in Java

In Java 8 or earlier: List<String> string = ...READ MORE

answered Jul 26, 2018 in Java by samarth295
• 2,220 points
4,764 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP