4

Suppose the following object structure:

class Super {}

class SubA extends Super {}
class SubB extends Super {}

I want to be able to have a variable that will hold the class object for either of my subclasses. I feel like this should do it:

Class<Super> classObj;

Then, I want to be able to something like this:

classObj = SubA.class;

or:

classObj = SubB.class;

This doesn't work though. I get the following error:

Type mismatch: cannot convert from Class<SubA> to Class<Super>

Any ideas why? What do I need to fix?

2
  • 1
    Is there a reason you need to store a variable and not just use getClass() when needed? Commented Jun 23, 2009 at 22:04
  • The reason is I am using enum types in a factory. The factory method takes one of the enums, and instantiates the appropriate class. There are other things stored in the enum as well, so this seemed to make sense to me, at least. Commented Jun 24, 2009 at 14:57

3 Answers 3

13

You need a bounded wildcard:

Class<? extends Super> classObj;

See the lesson on wildcards from the Java tutorials.

Sign up to request clarification or add additional context in comments.

Comments

1

As mmyers pointed out you could use wildcarding.

As an alternative, you could have the classes implement a common interface and then access them through that interface.

3 Comments

Don't mind me; I just keep a (rough) running total of people who misspell my name. I only started a month ago and I'm up to 17 already. And one of them is Jeff Atwood--I'm practically almost sort of famous!
Ah, my apologies, the situation has been rectified.
No problem; I'm used to it by now. (My brother once got a letter which was addressed to him, except that they misspelled all three of his names. He eventually got over it.)
1

Try this (fails to compile):

public class ListCopy {
  public static void main(String[] args) {
    List<String> stringList = new ArrayList<String>();
    List<Object> objectList = stringList;
  }
}

This will fail to compile even though String extends Object. Java stuff is not covariant - type parameters are erased, so the compiler does not know what will be there at runtime.

It's the same with Class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.