MAN*_*NHA 9 java variable-variables
我有一个bean类名称为"Bean1".在我的main方法中,我有一个包含变量名称的字符串.String str ="Bean1"; 现在我如何使用String变量来获取类并访问Bean属性.我是Java新手.请帮忙.
Tom*_*ros 13
一步步:
//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");
Run Code Online (Sandbox Code Playgroud)
对于最后一步,您需要知道bean的类型,或者需要知道您需要访问的属性的超类型.如果您在该类中拥有的所有信息都是带有名称的String,我想您不知道它.
使用反射,您可以访问类的方法,但在这种情况下,您需要知道要调用的方法的名称和输入参数类型.继续该示例,更改步骤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");
Run Code Online (Sandbox Code Playgroud)
如果你没有在运行时可以获得所有这些信息,也许你需要重新考虑你的设计.
Kel*_*Kel 11
您应该使用Java Reflection API:
Class c = Class.forName("package.name.Bean1");
Run Code Online (Sandbox Code Playgroud)
然后你可以使用c.newInstance()来实例化你的类.此方法使用不需要参数的构造函数.
详情请见:http://download.oracle.com/javase/tutorial/reflect/
| 归档时间: |
|
| 查看次数: |
22280 次 |
| 最近记录: |