views:

54

answers:

2

Given the a class with the following structure. I am trying to determine the type of the parameter T assigned by the caller of the 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 am trying to do this in Java. Does anyone know how/if I can do this? I don't really need an instance, I just need the Class definition.

+1  A: 

You can't, generics aren't available at runtime. If you had an instance of T, you could always check if T object was an instance of a specific class with instanceof.

This is due to type erasure.

An other way is to use the Class class as a parameter (see @ColinD's answer)

Colin Hebert
+2  A: 

You can't do that. What you could do is make the method signature like this:

public boolean isSupportable(Class<?> type)

Then you can use the given class to check the type.

ColinD