我可以按名称访问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
函数吗?
答案 0 :(得分:3)
您可以使用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);
答案 1 :(得分:1)
您正在寻找的是反射。 您可以执行以下操作:
void Func(String name, Integer value) {
Field f = getClass().getField(name);
f.setAccessible(true); // needed because f is not public
f.setInt(this, value)
}
但我可以添加一些评论吗?
答案 2 :(得分:0)
试试这个:
void Func(String name, Integer value) {
// Set A Value based on its name
Field f = getClass().getDeclaredField(name);
f.setAccessible(true);
f.set(this, value);
}
答案 3 :(得分:0)
也可以尝试:
package SO;
import java.lang.reflect.Field;
class Test {
Integer GoodVar;
Integer BadVar;
void Func(String name, Integer value) throws IllegalArgumentException, IllegalAccessException {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (name.equals(field.getName())) {
field.set(this, value);
}
}
}
// or a optimul way:
void Func1(String name, Integer value) throws IllegalArgumentException, IllegalAccessException, SecurityException,
NoSuchFieldException {
Field field = this.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(this, value);
}
void Init() throws IllegalArgumentException, IllegalAccessException {
Func("GoodVar", 2);
Func("BadVar", 1);
}
@Override
public String toString() {
return "[GoodVar->" + GoodVar + ",BadVar-> " + BadVar + "]";
}
}
使用示例Main方法:
package SO;
public class TestTest {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
Test test = new Test();
System.out.println(test);
test.Func("GoodVar", 1);
test.Func("BadVar", 2);
System.out.println(test);
}
}
打印:
[GoodVar->null,BadVar-> null]
[GoodVar->1,BadVar-> 2]