Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

variable variables - java String to class

I have got a bean class named Bean1. In my main method I have got a string containing the name of the variable:

String str= "Bean1"; 

Now how can I use the String variable to get the class and access the Bean properties?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Step by step:

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

For this last step, you need to know the type of the bean, or a supertype with the properties you need to access. And I guess that you don't know it, if all the information you have on the class is a String with its name.

Using reflection, you could access the methods of the class, but in this case, you would need to know the names and the input parameter types of the methods to be invoked. Going ahead with the example, change the steps 3 and 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");

Maybe you need to rethink your design, if you don't have all this information avalaible at runtime.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...