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 28, 2018 in Java by sharth
• 3,370 points
124 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 28, 2018 by Parth
• 4,630 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,890 points
703 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
• 54,020 points
213 views
0 votes
1 answer

Use of Static Keyword in a Class

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

answered May 28, 2018 in Java by Rishabh
• 3,580 points
105 views
+2 votes
3 answers

Listing all the subclasses of a specific class in Java

Try with BurningWave core library. Here an ...READ MORE

answered Dec 29, 2019 in Java by anonymous
• 370 points

edited Jan 9 by anonymous 2,248 views
0 votes
2 answers

How do i create generic array in Java

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

answered Feb 12 in Java by sama
8,206 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 18, 2018 in Java by sharth
• 3,370 points
67 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,890 points
8,115 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,150 points
71 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,890 points
115 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,190 points
895 views