Monday, July 18, 2005

Comparing classes in Java 1.4 compared to 1.3

Let's say you need to compare classes, checking, for example, whether a particular class is the same as this class. You might have something like this:

public class CorrectClass
{
  boolean isCorrectClass(Class cl)
  {
    return cl.equals(CorrectClass.class);
  }
}


This works with Java 1.3 or earlier, but gives you an error under 1.4:

Information: 1 error
Information: 0 warnings
Information: Compilation completed with 1 errors and 0 warnings
CorrectClass.java
Error: line (xxx) the symbol class$org$vshivers$test$CorrectClass conflicts with a compiler-synthesized symbol in org.vshivers.test.CorrectClass


To make it work properly under 1.4, use the afore-mentioned compiler-synthesized static member:

public class CorrectClass
{
  boolean isCorrectClass(Class cl)
  {
    return cl.equals(CorrectClass.class$org$vshivers$test$CorrectClass);
  }
}


Annoyingly, this is changed back to the original syntax in 5.0. Well, it's really more annoying that they changed this rather basic operation in 1.4, making it incompatible with every previous and subsequent version of Java.

No comments: