• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Generic Type on Class

 
Hank GU
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Class A extends BaseCls
Class B extends BaseCls

Class[] myArr = {A.class, B.class};

Eclipse promotes me that I can use generic type in Class i.e. Class<T>.

So how to create the generic type?
I tried Class<BaseCls>[] and Class<? extends BaseCls>[], both are not correct.

any1 can advise? thanks a lot!
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Hank GU:

I tried Class<BaseCls>[] and Class<? extends BaseCls>[], both are not correct.


Really? That second one, with the wildcard, looks correct to me.

In what way was it not correct? Can you post more code or more about the error?
 
Maneesh Godbole
Saloon Keeper
Posts: 11172
14
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try
 
Matt Gaunt
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a good reason for this.

It is not possible to instantiate arrays of objects with Generics. The problem lies in that fact that arrays are co-variant while generics are not.

Take for example two arrays:
Integer[] intArray=new Integer[6];
Number[] numArray=intArray;

This is possible as Number is a super class of Integer, and arrays are co-variant. Obviously if we tried to do numArray[3]=new Double(3.4);, a runtime error would be thrown.

Now we should remember generics are a compile time tool. And we should also remember that ArrayList<Number> is not a superclass of ArrayList<Integer>. And since this is the case, it is not possible for an array of ArrayList<Number> to be a super type of an array of ArrayList<Integer>. This doesn't sound like the answer to your orignal question but I am getting there.

The upshot of all this is that to avoid anyone ever trying to do this with arrays of generics, the compiler doesn't allow any generic arrays to be created. There is of course an exception to this rule, and that is where the generic is a wild card. So Class<?>[] classArray=new Class<?>[5] is allowed while Class<Integer>[] classArray=new Class<Integer>[5] is not.

There is quite a lot of documentation on this quirk. Search for 'generic arrays' and see what you find.

Regards

Matt Gaunt
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic