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,320 points
57 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 parth295
• 4,600 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,850 points
590 views
0 votes
1 answer

Get all the permutations of a string in Java

This is the recursive way of finding a ...READ MORE

answered May 10, 2018 in Java by sharth
• 3,320 points
79 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,540 points
53 views
0 votes
1 answer

Listing all the subclasses of a specific class in Java

There is a simple library available for ...READ MORE

answered Jun 7, 2018 in Java by geek.erkami
• 2,320 points
146 views
0 votes
1 answer

How do i create generic array in Java

Generic array creation is not allowed in Java. But, ...READ MORE

answered May 15, 2018 in Java by parth295
• 4,600 points
2,101 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,320 points
31 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,850 points
1,905 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
27 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,850 points
56 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
121 views