Field Subclass Accessing - Best Way Possible

和自甴很熟 提交于 2019-12-10 22:19:04

问题


So I've run into a bit of a problem dealing with preferences in a program. Considering the amount of times this will be used, having a single method would be best. A getter for each variable could potentially lead to a substantially larger file.

(5 fields * 200 to 300 classes = lots of wasted space)

I am trying to figure out how to access a Field with a defined and constant name from a subclass.

The super class is abstract, defined in a list and I have full access to it. This is the class where I would like the getter for the field to be in.

The way I would like it to work would be something like this:

import java.lang.reflect.Field;

public class Test {

    public Test() {
        final B b = new B();
        final C c = new C();
        System.out.println(b.getFoo());
        System.out.println(c.getFoo());
    }

    public static void main(String[] args) {
        new Test();
    }

    public class A {

        public String getFoo() {
            try {
                Field f = this.getClass().getField("FOO");
                f.setAccessible(true);
                return (String) f.get(null);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

    }

    public class B extends A {

        private static final String FOO = "$HOME.DIR/lib/res/image1.png";

    }

    public class C extends A {

        private static final String FOO = "$HOME.DIR/lib/res/image2.png";

    }

}

Expectedly, that did not work. The class A does not contain the field 'FOO'. Ideally, if it had worked I would have expected it to print out:

$HOME.DIR/lib/res/image1.png
$HOME.DIR/lib/res/image2.png

The ways I have (so far) seen that this would be possible:

  1. Reflection
  2. Using a Getter - Would like to avoid
  3. Using annotations

Using annotations was one way I could see it being possible, yet I generally do not like the overall concept of them, but if it is the only way I would of course accept it.

Thank you for reading this, hopefully you can provide insight.


回答1:


Can you describe your higher level problem in more detail, since it sounds like there may be some design changes that you could make to alleviate this issue. Accessing the fields of a subclass form a parent class via reflection just seems like a bad idea in general.

However, with that said, you need to use getDeclaredField instead of getField in order to access a private field by reflection.

E.g.

public String getFoo() {
        try {
            Field f = this.getClass().getDeclaredField("FOO");
            f.setAccessible(true);
            return (String) f.get(null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
}



回答2:


You could use a Map, something like this:

import java.util.HashMap;
import java.util.Map;

public class Test 
{
    public Test() 
    {
        final B b = new B();
        final C c = new C();
        System.out.println(b.getFoo());
        System.out.println(c.getFoo());
    }

    public static void main(String[] args)
    {
        new Test();
    }
}

class A 
{
    private static final Map<String, String> values;

    static
    {
        values = new HashMap<String, String>();
    }

    public String getFoo() 
    {
        return (values.get("FOO"));
    }

    protected static void addValue(final String key,
                                  final String value)
    {
        values.put(key, value);
    }
}

class B extends A 
{
    static
    {
        addValue("FOO", "$HOME.DIR/lib/res/image1.png");
    }
}

class C extends A 
{
    static
    {
        addValue("FOO", "$HOME.DIR/lib/res/image2.png");
    }
}


来源:https://stackoverflow.com/questions/15439730/field-subclass-accessing-best-way-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!