Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java class object from type variable

Tags:

Is there a way to get Class object from the type variable in Java generic class? Something like that:

public class Bar extends Foo<T> {     public Class getParameterClass() {         return T.class; // doesn't compile     } } 

This type information is available at compile time and therefore should not be affected by type erasure, so, theoretically, there should be a way to accomplish this. Does it exist?

like image 266
Alexander Temerev Avatar asked May 10 '10 08:05

Alexander Temerev


People also ask

What is object type variable in Java?

A variable of an object type is also called a reference. The variable itself does not contain the object, but contains a reference to the object. The reference points to somewhere else in memory where the whole object is stored.

How do you create a variable with an object type in Java?

Creating an ObjectDeclaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

How do I get the type of an object in Java?

Java provides three different ways to find the type of an object at runtime like instanceof keyword, getClass(), and isInstance() method of java. lang. Class.

What is getClass () in Java?

The Java Object getClass() method returns the class name of the object. The syntax of the getClass() method is: object.getClass()


1 Answers

This works:

public static class Bar extends Foo<String> {   public Class<?> getParameterClass() {     return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);   } } 
like image 165
sfussenegger Avatar answered Sep 22 '22 14:09

sfussenegger