javastaticfieldinherited

java set/get static inherited field on specified class


i'm in following situation:

public class SuperClass
{
        public static Object superClassStaticField;
}

public class ChildClass extends SuperClass
{
... some methods and fields
}

I have a method which looks like this:

...modifiers... void action(Class <? extends SuperClass> cls)
{
...
}

i would like to reach all elements whit reflection including superclass static fields which i (later in ChildClass) initalize, but looks like here is some logic fails in reflection:

The superClassStaticField is in the Superclass, so if i try to reach with:

cls.getClass().get[Declared]Field("superClassStaticField");

i will get java.lang.NoSuchFieldException

So i must reach trouth the SuperClass:

SuperClass.class.getDeclaredField("superClassStaticField").get(null);

will work successfully, but if there is more than one ChildClass works in same Runtime, my program getting crazy. I think beacuse all method reach same Object wich is declared in SuperClass.

But how can i reach the actually given class static field?

i tried:

SuperClass.class.getDeclaredField("superClassStaticField").get(cls);

But the result is same.

How can i reach it?

Edit: i would like get/set now only static fields, create a new instance is not safe, (sour it's have empty constructor? and will modify nothing?)


Solution

  • But how can i reach the actually given class static field?

    There is only a single static field. You don't end up with one static field per subclass. It sounds like you need to take a different approach. We can't give you much advice about what that approach should be, as we don't know what you're trying to achieve. Perhaps a Map<Class, Object> is what you're after?