I have got a bean class names as "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. I am new to Java. please help.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Duplicate of Does Java support variable variables?
Java doesn't support dynamically getting a variable based on a string of its name (also known as variable variables). There's likely a different way of doing what you're trying to do, such as using a Map object to map names to beans. If you edit your question to explain what you want to do in a bit more detail, we might have some more concrete answers.
(On the other hand, if the question was about a class called Bean1, then Kel's right.)
Step by step:
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:
Maybe you need to rethink your design, if you don't have all this information avalaible at runtime.
You should use Java Reflection API:
Then you may use c.newInstance() to instantiate your class. This method uses constructor which does not require parameters.
See details here: http://download.oracle.com/javase/tutorial/reflect/