Question

I need to get the Class of an object at runtime.

For an non-abstract class I could do something like:

public class MyNoneAbstract{
    public static Class MYNONEABSTRACT_CLASS = new MyNoneAbstract().getClass();

But for an abstract class this does NOT work (always gives me Object)

public abstract class MyAbstract{
    public static Class MYABSTRACT_CLASS = MyAbstract.class.getClass();

This code will be running in JavaME environments.

Was it helpful?

Solution

You just need

MyAbstract.class

That expression returns the Class object representing MyAbstract.

OTHER TIPS

The code you want in the abstract case is:

public abstract class MyAbstract{
    public static Class MYABSTRACT_CLASS = MyAbstract.class;
}

although I personally wouldn't bother defining the constant and just used MyAbstract.class throughout.

I would have expected the code you wrote to have returned the class 'Class', not the class 'Object'.

I think more information is required here. In Java, an abstract class cannot be instantiated. That means an Object at runtime cannot have its class be abstract. It would need to be a subclass that implements all abstract methods. In JavaME, Object.getClass() should be all you need. Are you somehow trying to reconstitute your class hierarchy at runtime?

In that case, you could implement something like this instead:

public String getClassHierarchy() {
    return super.getClassHierarchy() + ".MyAbstract";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top