9

我有一个名为Bean1. 在我的主要方法中,我有一个包含变量名称的字符串:

String str= "Bean1"; 

现在如何使用该String变量来获取类并访问 Bean 属性?

4

3 回答 3

14

一步步:

//1. As Kel has told you (+1), you need to use 
//Java reflection to get the Class Object.
Class c = Class.forName("package.name.Bean1");

//2. Then, you can create a new instance of the bean. 
//Assuming your Bean1 class has an empty public constructor:
Object o = c.newInstance();

//3. To access the object properties, you need to cast your object to a variable 
// of the type you need to access
Bean1 b = (Bean1) o;

//4. Access the properties:
b.setValue1("aValue");

对于这最后一步,您需要知道 bean 的类型,或者具有您需要访问的属性的超类型。而且我猜你不知道,如果你在这个类上的所有信息都是一个带有它的名字的字符串。

使用反射,您可以访问类的方法,但在这种情况下,您需要知道要调用的方法的名称和输入参数类型。继续示例,更改步骤 3 和 4:

// 3. Get the method "setValue1" to access the property value1, 
//which accepts one parameter, of String type:
Method m=c.getMethod("setValue1", String.class);

// 4. Invoke the method on object o, passing the String "newValue" as argument:
m.invoke(o, "newValue");

如果您在运行时没有所有这些信息可用,也许您需要重新考虑您的设计。

于 2010-10-27T07:14:43.603 回答
13

您应该使用 Java 反射 API:

Class c = Class.forName("package.name.Bean1");

然后你可以使用c.newInstance()来实例化你的类。此方法使用不需要参数的构造函数。

在此处查看详细信息:http: //download.oracle.com/javase/tutorial/reflect/

于 2010-10-27T06:49:39.977 回答
2

Java是否支持可变变量?

Java 不支持根据名称字符串动态获取变量(也称为变量变量)。可能有不同的方式来做你想做的事情,例如使用 Map 对象将名称映射到 bean。如果您编辑您的问题以更详细地解释您想要做什么,我们可能会有一些更具体的答案。

(另一方面,如果问题是关于一个名为 Bean1 的类,那么 Kel 是对的。)

于 2010-10-27T07:03:31.240 回答