我可以按名称访问Class属性吗?

例如:

class Test {
    Integer GoodVar;
    Integer BadVar;
    ...

    void Func(String name, Integer value) {
        // Set A Value based on its name
    }

    void Init() {
        Func("GoodVar", 2);
        Func("BadVar", 1);
    }
}


有人可以编码Func功能吗?

最佳答案

您可以使用switch语句,在JDK 7中允许使用字符串(请参见:http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html)。就像是:

switch (name) {
     case "GoodVar":
         GoodVar = value;
         break;
     case "BadVar":
         BadVar = value;
         break;
     default:
         throw new IllegalArgumentException("Invalid name: " + name);
 }


在JDK 7之前,您可以使用if语句。
另一种方法是使用反射(请参阅:http://docs.oracle.com/javase/tutorial/reflect/index.html),但是它很慢,例如:

Field f = getClass().getField(name);
if (f!=null){
 f.setAccessible(true);
 f.setInt(this, value);
}else
  throw new IllegalArgumentException("Invalid name: " + name);

07-26 05:33
查看更多