Generic with instanceof
Once in a while you feel the need to decide from which type a Generic really is.
As a general rule the following code points out a bad design. Nevertheless, he helps sometimes…
package com.sowas.javawiki; import java.lang.reflect.ParameterizedType; public class GenericType{ @SuppressWarnings("unchecked") public static void main(String[] args) throws InstantiationException, IllegalAccessException{ Class c = new MyClass<String>(){}.getType(); System.out.println(c); System.out.println((c.newInstance() instanceof String)?"String":"No String"); } static class MyClass<T> { Class<T> type; @SuppressWarnings("unchecked") public MyClass(){ type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } public Class<T> getType(){ return type; } } }