Java class literal on CLDC
In Java, a class literal is a construct of the form String.class, which returns the Class object that corresponds to the named class. You can use this to test the exact class of an object, like this:
boolean isInteger(Object obj) {
return obj.getClass() == Integer.class;
}
(A similar goal can be achieved by using instanceof, even though the semantics and the performance are not exactly the same.)
If you try to use the class literal on CLDC 1.0, it won’t work. You get at compile-time the rather funny error message
class file for java.lang.NoClassDefFoundError not found.
The explanation is that, up to and including Java 1.4, the class literal is emulated this way:
static Class class$java$lang$Integer;
static Class class$(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new NoClassDefFoundError();
}
}
boolean isInteger(Object obj) {
return obj.getClass() ==
(class$java$lang$Integer != null ?
class$java$lang$Integer :
(class$java$lang$Integer = class$("java.lang.Integer")));
}
So the innocent-looking Integer.class is translated into a bunch of code, which can throw a new unchecked exception, NoClassDefFoundError. The problem is that CLDC 1.0 doesn’t provide this exception class, so you get a compilation error.
The solution? Use instanceof if possible. Another solution is to use a static final member initialized by calling getClass() on a dummy instance.
static final Class INTEGER_CLASS = new Integer(0).getClass();