在 Java 中,如何获取给定字符串名称的属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2043471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java, how to get attribute given the string with its name?
提问by Fluffy
I'm sorry for asking this sort of questions, but I really couldn't find the answer in Google. So say I have a class with private String myColor
and I have a string "myColor". Now I want to manipulate the myColor
attribute. How can I do that?
我很抱歉问这种问题,但我真的无法在谷歌中找到答案。所以说我有一个类,private String myColor
我有一个字符串“myColor”。现在我想操纵该myColor
属性。我怎样才能做到这一点?
Edit:Sorry for an unclear question, I guess the best way is to explain what I need it for. I've got a Swing form and want to use the preferences api to set the values of fields when loading gui. So I can read all the fields and then do outputDirectoryTextField.setText(valueFromPrefsAPI);
for each of them, but that seems to be a bit of unneeded coding so I want to have an array(hash?) with the names of fields and loop through them, like this:
编辑:抱歉有一个不清楚的问题,我想最好的方法是解释我需要它做什么。我有一个 Swing 表单,想在加载 gui 时使用首选项 api 来设置字段的值。所以我可以读取所有字段,然后outputDirectoryTextField.setText(valueFromPrefsAPI);
为每个字段执行,但这似乎是一些不需要的编码,所以我想要一个包含字段名称的数组(哈希?)并循环遍历它们,如下所示:
String[] myTextInputs = {"thisInput", "thatInput"};
for (String inputName : myTextInputs) {
String value = prefs.get(inputName, "");
/* some code I'm seeking to find out*/.setText(value);
}
采纳答案by Itay Maman
You can use reflection to inspect the content of any object, as follows:
您可以使用反射来检查任何对象的内容,如下所示:
Object o = ...; // The object you want to inspect
Class<?> c = o.getClass();
Field f = c.getDeclaredField("myColor");
f.setAccessible(true);
String valueOfMyColor = (String) f.get(o);
Note that getDeclaredField() will only return field's declared by the object's class. If you're looking for a field that was declared by a superclass you should loop over all classes of the object (by repeatedly doing c = c.getSuperclass() until c == null)
请注意, getDeclaredField() 将仅返回由对象的类声明的字段。如果您正在寻找由超类声明的字段,您应该遍历对象的所有类(通过重复执行 c = c.getSuperclass() 直到 c == null)
If you want to change the value of the field you can use the set method:
如果要更改字段的值,可以使用 set 方法:
f.set(o, "some-new-value-for-field-f-in-o")
Additional details: https://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html
其他详细信息:https: //docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getField(java.lang.String)
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getField(java.lang.String)
You can use getField(...) which will search on super class if not found in class.
您可以使用 getField(...) 如果在类中找不到,它将搜索超类。
回答by zmbush
You must create a 'mutator' to modify private member variables.
您必须创建一个“mutator”来修改私有成员变量。
class example{
private string myColor;
public void changeColor(string newColor){
myColor = newColor;
}
}
回答by Mickel
If I understand your question correctly... You should create public getters and setters:
如果我正确理解您的问题...您应该创建公共 getter 和 setter:
public void setMyColor(String color) {
this.myColor = color;
}
public String getMyColor {
return this.myColor;
}
回答by Jay R.
Based on the edit, my suggestion is to use a Map to contain a map of preference name to appropriate text field or other text component. Just build the map when you build the user interface.
根据编辑,我的建议是使用 Map 将首选项名称映射到适当的文本字段或其他文本组件。只需在构建用户界面时构建地图。
Map<String, JTextField> guiFields = new HashMap<String, JTextField>();
Then you can have the code do
然后你可以让代码做
guiFields.get(inputName).setText(value);
回答by fastcodejava
It depends where you want to do this. Inside the class you simply whatever with it, e.g:
这取决于您想在哪里执行此操作。在课堂上,你可以随意使用它,例如:
myColor = "blah blah";
From outside, you need to have some public method generally as other posts indicated. In all cases, you have to be careful if your environment in multi-threaded. Class level variables are not thread safe.
从外部来看,您通常需要像其他帖子所指出的那样拥有一些公共方法。在所有情况下,如果您的环境是多线程的,您必须小心。类级变量不是线程安全的。