Wednesday, December 29, 2010

More Oddities

Nothing particularly enlightening, this is more a scratchpad for me.

Taking yesterday's code, I got to thinking what happens if I compile a class external to our friend, the class that appears to violate the language spec. It has two methods:

/** This code compiles in Eclipse 3.4 but does not in Eclipse Helios */
public class ErasureTest extends TestCase {
.
.
.
public String sameMethod(Class clazz) {
return STRING;
}

public Integer sameMethod(Class clazz) {
return INTEGER;
}
The Java Language Spec says this should be forbidden but the JVM seems happy with it. Whatsmore, I now have a class that looks like this:

package com.henryp.lang;

public class ErasureCaller {
public static void main(String[] args) {
new ErasureTest().sameMethod(ErasureCaller.class);
}
}

And upon compilation, I get:

phillip:Phill henryp$ javac -d bin -cp .:/Users/henryp/Documents/workspace/Test/bin:/Users/henryp/.m2/repository/junit/junit/3.8.2/junit-3.8.2.jar com/henryp/lang/ErasureCaller.java
com/henryp/lang/ErasureCaller.java:5: cannot find symbol
symbol : method sameMethod(java.lang.Class<com.henryp.lang.ErasureCaller>)
location: class com.henryp.lang.ErasureTest
new ErasureTest().sameMethod(ErasureCaller.class);
^
1 error
because the generic information in the signature is not entirely erased as we saw yesterday.

But this is fine:

package com.henryp.lang;

public class ErasureCaller {
public static void main(String[] args) {
new ErasureTest().sameMethod(String.class);
}
}
As if the erasures were not, well, erased at all. Which leaves me wondering what's the use of erasures.

"Type erasure exists so that new code may continue to interface with legacy code."
(Type Erasure, The Java Tutorials)

But this seems to be a unidirectional relationship. New code can use old binaries but type erasure does not mean old code can use new binaries. Setting the -source and -target switches on javac to 1.4 does not mean generic code will compile.

No comments:

Post a Comment