Tom,
Thank you for your explanation, I'm sure it will finally hit home after
a couple of re-reads, but from what I understand the inclusion of
generics has been bundled with a new Class class that has some kind of
[invisible?] object hierarchy of its own. Presumably this hierarchy
exists at some stage during compilation, which is how the compiler
knows that i's type isn't convertible to s's type. If you reflect over
either of the types at runtime they're both the same java.lang.Class,
but then that's probably something to do with the dreaded "type
erasure". I welcome your comments.
Cheers,
Jono
Thomas Hawtin wrote:
Jono wrote:
Hi everyone,
I have a reasonably strong .NET background and I have a problem
understanding the Class class in Java. The Type class in .NET (along
with the typeof() operator and System.Object's GetType() method) seems
pretty straightforward to me: an instance of the Type class is
instantiated for every type loaded into the system (even with
generics). But it's not so easy to understand with Java, it seems. If I
try to compile the sample code below it fails on line 3 of the main
method. If I explicitly cast the left-hand and right-hand sides of the
equality expression (as per line 4) to Class, then the compiler is
happy. Please could someone let me know what the subtle difference is
that I am missing out on?
public class NewClass {
public static void main(String[] args)
{
Integer i = new Integer(123);
String s = "456";
//System.out.println(i.getClass() == s.getClass()); //
compilation failure
System.out.println(((Class)i.getClass()) ==
((Class)s.getClass()));
}
}
An object of type Class<capture of ? extends Integer> cannot be the same
object as an object of type Class<capture of ? extends String> (unless
you write unchecked code, and null is an odd case). The is no type T
such that Class<T> is compatible with both of those types. No T
simultaneously extends both String and Integer.
Similarly the expression "i instanceof String" and "i == s" are nonsense
and will not compile.
Tom Hawtin
but the rule itself makes no sense to me.
The language allows many comparisons that can never have a true result.
For example, 2==3 is a valid comparison, with the result false.
accepted.
false, that the compiler rejects the comparison at compile time.