How can I get the the superclass of a Class instance in Java ME. That is, fake the Class.getSuperclass() functionality with the limited functionality available in CLDC 1.1?
What I want to do is to let the abstract super class do something like this:
public Styler getStylerForViewClass(Class clazz) {
Styler s = stylers.get(clazz);
if (s == null) {
for (Class c = clazz; s == null; c = c.getSuperclass()) {
if (c == Object.class) {
throw new IllegalArgumentException("No Styler for " + clazz.getName());
}
s = createStylerForViewClass(c);
}
stylers.put(clazz, s);
}
return s;
}
public Styler createStylerForViewClass(Clazz clazz) {
if (clazz == View.class) {
return new DefaultStyler();
} else {
return null;
}
}
Sub classes could then add specializations like this:
public Styler createStylerForViewClass(Class clazz) {
if (clazz == SpecialView.class) {
return new SpecialStyler();
} else {
return super.createSylerForViewClass(clazz);
}
}
As you have already discovered, MIDP does not provide a method for getting the superclass of a class, nor for enumerating all classes in the application.
So all you can do is keep track of the class hierarchy yourself.
Having a common superclass makes it slightly easier, because you can have the new object add its own class to a global class collection (if not already present) in the superclass constructor:
but unfortunately this will not work for abstract classes, because no instances are ever created.
Keeping track of superclass/subclass relations for a known subset of classes is easy enough. e.g.:
But this can “miss” intermediate classes that are added later, e.g. if you have these classes:
and add
AandCto the tree and asked it for the superclass ofCit would give youA, and if you later addedBit would replaceAas the superclass ofC, but not until the wrong styler had been returned for some instances ofC.So I think you will have to add the restriction that ancestor classes (that have stylers defined for them) must be added to the tree first. Possibly from the static initializer block of the class that overrides
createStylerForViewClass, or the static initializer of the view class itself.I did think of one other evil hack, but I can’t really recommend it:
Viewconstructor, create a newException, but don’t throw it.System.errfor your own writer that writes to aByteArrayOutputStreamprintStackTrace()on the exceptionSystem.errto its original valueByteArrayOutputStream. The names of the intermediate classes’ constructors will be in the stack trace. Now you can look them up usingClass.forName()and add them to the tree.