tags:

views:

199

answers:

3

So i need to get the Class of an object at runtime, and sorry guys Javas not my home ;0)

For an none 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.

Thanks for the help...

+2  A: 

You just need

MyAbstract.class

That expression returns the Class object representing MyAbstract.

skaffman
It will on CLDC1.1, but not on CLDC1.0 :: http://blog.javia.org/java-class-literal-on-cldc/
funkybro
A: 

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'.

DJClayworth
I explained myself poorly. I need to return the Class of a related helper class and the static variable is simply for convenienceMany thanks for your response
Philip.ie
A: 

I think more information is required here. In Java, an abstract class cannot be instantciated. 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 that instead:

public String getClassHierarchy() { return super.getClassHierarchy() + ".MyAbstract"; }

QuickRecipesOnSymbianOS