[jboss-dev] generic collection item type

Adrian abrock at redhat.com
Mon Jul 30 10:04:24 EDT 2007


On Mon, 2007-07-30 at 15:37 +0200, Adrian wrote:
> But if it is on a superclass, there is no way to get
> at this information.
> 
> In the main java reflection api:
> 
> Class.getGenericSuperClass() returns a ParameterizedType
> 
> but from that ParameterizedType there is no route
> to get the generic interfaces.

The only way I can see to do it is hack around
with matching parameter type names on the raw
types and their "generic" interfaces. 
Then you can work your back and get the real type
passed to that parameter.

e.g.

   public static void main(String args[]) throws Exception
   {
      System.out.println("Type of collection: " + Collection.class.getTypeParameters()[0]);
      
      Class myClass1 = MyClass2.class.getSuperclass();
      System.out.println("Type of MyClass1: " + myClass1.getTypeParameters()[0]);
      
      ParameterizedType collection = (ParameterizedType) myClass1.getGenericInterfaces()[0];
      System.out.println("Type on interface: " + collection.getActualTypeArguments()[0]);
   }
   
   public class MyClass1<T> extends AbstractCollection<T> implements Collection<T>
   {
      public Iterator<T> iterator()
      {
         return null;
      }

      public int size()
      {
         return 0;
      }
   }
   
   public class MyClass2 extends MyClass1<String> {}

produces the output:

Type of collection: E
Type of MyClass1: T
Type on interface: T

So you can match the type name T of the "raw" MyClass1
with the parameter name passed to its the collection interface, also T.

The first line of output just shows that the Collection class
actually declared this parameter as E.

-- 
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
Adrian Brock
Chief Scientist
JBoss, a division of Red Hat
xxxxxxxxxxxxxxxxxxxxxxxxxxxx




More information about the jboss-development mailing list