T
Thomas Hawtin
Jono said: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