变量中的属性名称

时间:2014-11-09 10:28:45

标签: java

;如何将String变量的值用作属性或方法名称?

想做类似的事情:

class Person {
    public String firstname;
}

String myAttributeName="firstname";
Person obj = new Person();
String firstNameOfObj = obj.{myAttributeName};

1 个答案:

答案 0 :(得分:3)

如果真的想要这样做,你可以使用反射:

Person obj = new Person();
Method method = Person.class.getMethod("getFirstname");
String firstname = method.invoke(obj); 

但正如评论中所提到的,您最好使用地图来保存属性值:

class Person {
   private Map<String,Object> attrs = new HashMap<>();

   public void setAttribute(String attr, Object value)
   {
      attrs.put(attr,vaue);
   }

   public Object getAttribute(String attr)
   {
      attrs.get(attr);
   }

}

Person person = new Person();
person.setAttribute("firstname","patrick");
String firstname = (String)person.getAttribute("firstname");