tags:

views:

57

answers:

4

How to valid the type of generic parameter in Java (with out using reflection if possible) ?

The target is something like C# allow to do:

public <T> void  doStaff() {

  if(T is Type1) {

  }

  if(T is Type2) {

  }

}

How to write method like that in Java ?

+3  A: 
public <T> void  doStaff(Class<T> type) {
    if (Type1.class.isAssignebleFrom(type)) {.. }
    if (Type2.class.isAssignebleFrom(type)) {.. }
}
Bozho
+3  A: 

Generic information in Java is erased at runtime. You can never do something like "T instanceof". However, you can pass something into the method, and do an instanceof a reference, like so:

public T void  doStaff(T t) {
    if (t instanceof Type1) {...}

}

To make it clearer, T is a generic parameter, that goes away at runtime. t is a reference that you can work on at runtime.

hvgotcodes
A: 

Use the Class.isAssignableFrom(Class) method on the Type's class

import java.io.Serializable;
import java.util.Hashtable;

    public class Test<T> {

        private T t;

        public void set(T t)   {
           this.t = t;
        }

        private T get()  {
           if(Serializable.class.isAssignableFrom(t.getClass())) {
              System.out.println("Hurray!!!");
           }
           return t;
        }

        public static void main(String[] args) {
           Test<Hashtable> test = new Test<Hashtable>();
           test.set(new Hashtable());      
           test.get(); // prints Hurray!!
        }

    }
naikus
A: 

Java uses type erasure to handle generics. This means that all information about generics is only checked at compile time, and the resulting bytecode has no reference at all to the fact that generics were used.

List<String> stringList = new ArrayList<String>();
stringList.add("foo");
String s = stringList.get(0);

will (after doing compile time checks on the generic parameters) will basically compile to the same thing as

List stringList = new ArrayList();
stringList.add("foo");
String s = (String)(stringList.get(0));

What this means is that you can't do any runtime checks on a generic parameter directly, like what you're trying to do.

If you have a specific object of a genericized type, you can use the instanceof operator to determine if that object is an instance of a specific class, but you can't do anything on the actual generic parameter itself, because that gets type-erased at runtime.

demeteloaf