按名称获取实例变量

时间:2014-04-29 11:33:00

标签: java instance instance-variables

我有两个班,A和B.

B包含A的实例。我想通过名称从B返回A的实例:

class A
{
    public String name;

    public A (String name)
    {
        this.name = name;
    }
}

class B
{
    public A a1;
    public A a2;
    public A a3;

    public B ()
    {
        this.a1 = new A ("a1");
        this.a2 = new A ("a2");
        this.a3 = new A ("a3");
    }

    public A get_A_byName (String name)
    {
        // Is it possible to write something like this? B will always contain only instances of A
        for (A a : B.variables)
        {
            if (a.name.equals(name))
            {
                return a;
            }

            // Or in case A doesn't have a variable "name", can I get an A instance by its declared name in B?
            if (a.getClass().getName().equals(name))
            {
                return a;
            }
        }
    }
}

是否可以执行代码评论中描述的内容?提前致谢。

1 个答案:

答案 0 :(得分:5)

这或多或少是用于将密钥(在本例中为字符串)与对象配对的哈希映射

class B
{
    private HashMap<String,A> theAs=new HashMap<String,A>(); //give better name


    public B ()
    {
        theAs.put("a1",new A ("a1")); //A probably doesn't need to keep its own name internally now, but have left it as its in your original code
        theAs.put("a2",new A ("a2"));
        theAs.put("a3",new A ("a3"));
    }

    public A get_A_byName (String name)
    {
        return theAs.get(name);
    }
}

注释

  • 在Java 7+中,您无需添加第二个<String,A>钻石 推理会做,因此在Java 7或更高版本中它将是:

    private HashMap<String,A> theAs=new HashMap<>();
    
相关问题