使用"String concatation "我可以通过它的完全限定类名获得一个类对象:
String s = "Foo";// package
String s2 = "bar";// Class
Class c=Class.forName(s+"."+s2);
如何做Object的等效:
String s = "Foo";// portion of Object's name
String s2 = "bar";// another portion of Object's name
JButton foo_Bar = new JButton();
JButton o = Object.forName(s+"_"+s2);// Using "String concatenation" (key phrase) to obtain Object
或任何方式(简单或其他)保留使用"字符串连接"
只有当您试图获取的对象是一个类变量(在方法之外定义,作为类的一部分)时才有可能。
你可以使用Java的反射API通过字段名来访问字段的值。实现这一点的代码如下所示:
public class Example {
public JButton foo_bar = new JButton("I am a Button");
public void fieldByNameExample() throws NoSuchFieldException, IllegalAccessException {
// The two parts we're going to concatenate to make "foo_bar"
String partA = "foo";
String partB = "bar";
// Gets the Field object representing the field by its name.
Field field = Example.class.getDeclaredField(partA + "_" + partB);
// Retrieves the contents of the Field for this object.
JButton value = (JButton) field.get(this);
System.out.println(value.getText()); // prints: "I am a Button"
}
}
在调用上述方法时,需要捕获NoSuchFieldException
(当没有给定名称的字段时抛出)和IllegalAccessException
(当您试图获取其内容的字段在当前上下文中不可访问时抛出)。
如前所述,只有在将变量声明为类中的字段时才有效。在方法内部声明变量是不可能的(因为编译器会在编译过程中丢弃这些局部变量的名称)。
请注意,反射API可能相对较慢,并且使用它通常不是最佳解决方案。你还应该寻找其他解决问题的方法。如果你仍然坚持使用反射,我建议你先看看关于Java反射的文档,因为如果你不知道你在做什么,反射API是相当难以使用的。