This discussion is archived
4 Replies Latest reply: Aug 26, 2010 12:51 AM by 800025 RSS

How to initialize generic class ?

843793 Newbie
Currently Being Moderated
How to initialize generic class like below ?
class X<T> {
     protected final Class<T> c;

     public X() {
          // how to initialize c to T class ?
     }
}
  • 1. Re: How to initialize generic class ?
    800025 Explorer
    Currently Being Moderated
    This is generally done as follows:
    public class X<T> {
    
        protected final Class<T> c;
    
        public X(Class<T> c) {
         this.c = c;
        }
    
    }
    Piet
  • 2. Re: How to initialize generic class ?
    843793 Newbie
    Currently Being Moderated
    Is this possible in no-parameter (default) constructor ?
  • 3. Re: How to initialize generic class ?
    EJP Guru
    Currently Being Moderated
    No, that's why [this is generally done as follows|http://forums.sun.com/thread.jspa?messageID=11039686#11039686].
  • 4. Re: How to initialize generic class ?
    800025 Explorer
    Currently Being Moderated
    The general answer should be: no.

    However, when creating a subclass from a parameterized class, the type can be obtained. If you would follow this trail, I suggest you declare the class X<T> as abstract, to force users to subclass it.
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    
    @SuppressWarnings("unchecked")
    public class X<T extends Object> {
    
        public static void main(String[] args) {
         System.out.println("Direct instantiations:");
         System.out.println(new X<Integer>().getTypeName());
         System.out.println(new X<String>().getTypeName());
         System.out.println(new X().getTypeName());
    
         System.out.println("Subclassed instantiations:");
         System.out.println(new X<Integer>() {}.getTypeName());
         System.out.println(new X<String>() {}.getTypeName());
         System.out.println(new X() {}.getTypeName());
        }
    
        private final Class<T> clazz;
    
        public X() {
         Class<?> attempt = null;
    
         Type genericSuperClass = this.getClass().getGenericSuperclass();
         if (genericSuperClass instanceof ParameterizedType) {
             ParameterizedType parameterizedType = (ParameterizedType) genericSuperClass;
    
             for (Type actual : parameterizedType.getActualTypeArguments()) {
              if (actual instanceof Class<?>) {
                  attempt = (Class<?>) actual;
                  break;
              }
             }
         }
         if (attempt == null) {
             attempt = Object.class;
         }
         clazz = (Class<T>) attempt;
        }
    
        public String getTypeName() {
         return clazz.getName();
        }
    
    }
    Piet