my dog learned polymorphism
The moose likes Java in General and the fly likes Java Generic Type on Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Generic Type on Class" Watch "Java Generic Type on Class" New topic

Java Generic Type on Class

Hank GU
Ranch Hand

Joined: Jan 11, 2004
Posts: 44
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!

=======================<br />SUN: SCJP, SCWCD, SCBCD, SCEA, SCDJWS<br />BEA: Certified Architect<br />M$: MCP, MCSA
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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?

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10815


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Matt Gaunt
Ranch Hand

Joined: Sep 05, 2003
Posts: 34
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.


Matt Gaunt
I agree. Here's the link:
subject: Java Generic Type on Class
It's not a secret anymore!