Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

java - Why can't assign I <? extends Type> to <Type>?

The following statements:

URLClassLoader ucl = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<URLClassLoader> uclc = ucl.getClass();

fail with error:

Type mismatch: cannot convert from Class<capture#2-of ? extends URLClassLoader> to Class<URLClassLoader>

Why do I need a cast, here?

I found several posts explaining why You can't do the reverse (assign T to a ), but that's (kind of) obvious and understood.

NOTE: I am coding this under eclipse Luna, so I don't know if it's a Luna Quirk or if there's something I really dont understand in generics.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Covariance vs contravariance vs invariance

  • Class<? extends URLClassLoader> is invariant.

As a result,

Class<? extends URLClassLoader> is not a subtype of Class<URLClassLoader>


In Java a variable can hold a reference of an instance of same type or subtype.

Hence,

Class<URLClassLoader> uclc = ucl.getClass();

is invalid.

On the other hand,

Class<? extends URLClassLoader> uclc = ucl.getClass();

would be valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...