2010-10-27 104 views
7

我有一个bean类名称为“Bean1”。在我的主要方法中,我得到了一个包含变量名称的字符串。 String str =“Bean1”;现在我该如何使用String变量来获取类并访问Bean属性。我是Java新手。请帮忙。java String to class

+0

我试图实现的功能是“在应用程序的运行时创建了一个Inetrface和相关的Bean类,我能够获得bean类和接口所在的路径。得到了一个类“SrcInfo”,其中Bean的mehtod列表和参数作为类变量提供,现在我必须动态创建一个java类,我需要创建一个方法,它将Bean对象作为参数并返回一个HashMap操纵Bean对象中包含的数据,因此我得到了Bean类的名称作为字符串变量 – 2010-10-27 08:07:01

回答

10

您应该使用Java反射API:

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

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

在这里看到的细节:http://download.oracle.com/javase/tutorial/reflect/

+2

他可能还需要一个Bean1的实例 – cherouvim 2010-10-27 06:52:57

+0

我试图实现的功能是“有一个Inetrface和相关的Bean类在运行时间的应用程序。我能够获得bean类和接口所在的路径。现在我有一个类“SrcInfo”,其中Bean的mehtod列表和参数作为类变量提供。现在我必须动态创建一个java类,我需要创建一个将Bean对象作为参数的方法,并通过操作Bean对象中包含的数据来返回HashMap。因此,我得到了bean类的名称作为字符串变量。 – 2010-10-27 08:06:44

+0

@MANU SINHA:你应该在问题中包含这些信息(请编辑它)。这是获取有用答案的重要信息 – 2010-10-27 08:20:18

1

Does Java support variable variables?

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

(在另一方面,如果这个问题是关于一个叫Bean1,然后凯尔的权利类)。

8

循序渐进:

//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"); 

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