Type determination for a generic method parameter at run time

Given a class with the following structure. I am trying to determine the type of parameter T assigned by the caller of a generic method.

public class MyClass{ public <T> Boolean IsSupportable() { Class typeOfT; // Need to determine Class for generic parameter T // Business Logic goes here return true; } } 

In C #, I would use "default (T)" or "typeof (T)", but I'm trying to do this in Java. Does anyone know how I can do this? I don't need an instance, I just need a class definition.

+4
source share
2 answers

You cannot do this. What you can do is to sign the method as follows:

 public boolean isSupportable(Class<?> type) 

Then you can use this class to check the type.

+4
source

You cannot, generics are not available at runtime. If you have an instance of T, you can always check if the T object instance of a particular class with instanceof .

This is due to type erasure .

Another way is to use the Class Class as a parameter (see @ColinD answer )

+1
source

All Articles