你在寻找反思。有一个关于该主题的Java 教程可以帮助您入门,然后有很多很多库可以使反射更容易,例如Commons BeanUtils和Spring 的 util 包中的几个类。几乎所有的框架都会在其中包含某种反射辅助类,因为直接使用反射非常麻烦。
作为您的案例的快速示例,使用Commons BeanUtils.getProperty(),您可以说:
fp.textField.settext((String) BeanUtils.getProperty(b, str));
这是一个以手动方式执行此操作的完整示例,因此您可以了解它是如何适应的:
import java.lang.reflect.Field;
public class BasicReflectionGettingFieldValues {
public static void main(String[] args) {
FieldPanel fp = new FieldPanel();
Book b = new Book("Mostly Harmless", "Douglas Adams");
for (String str : Arrays.asList("author", "title")) {
fp.namelabel.settext(str);
fp.textField.settext(getField(b, str));
}
}
private static String getField(Book b, String str) {
try {
Field field = Book.class.getDeclaredField(str);
field.setAccessible(true);
return (String) field.get(b);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("Bad field name: " + str, e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Failed to access field " + str + " after making it accessible", e);
}
}
static class Book {
private String title;
private String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
}
static class TextField {
void settext(String s) {
System.out.println("Setting text field to '" + s + "'");
}
}
static class NameLabel {
void settext(String s) {
System.out.println("Setting name label to '" + s + "'");
}
}
static class FieldPanel {
private NameLabel namelabel = new NameLabel();
private TextField textField = new TextField();
}
}