java 字符串到类
我有一个名为 Bean1 的 bean 类。在我的 main 方法中,我得到了一个包含变量名称的字符串:
String str= "Bean1";
现在如何使用 String
变量来获取类并访问 Bean 属性?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一步一步:
对于最后一步,您需要知道 bean 的类型,或者具有您需要访问的属性的超类型。我猜你不知道,如果你拥有的关于类的所有信息都是一个带有其名称的字符串。
使用反射,您可以访问类的方法,但在这种情况下,您需要知道要调用的方法的名称和输入参数类型。
继续该示例,更改步骤 3 和 4:
如果您在运行时没有提供所有这些信息,也许您需要重新考虑您的设计。
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.
您应该使用 Java Reflection API:
那么您可以使用 c.newInstance() 来实例化您的类。该方法使用不需要参数的构造函数。
请参阅此处的详细信息:http://download.oracle.com/javase/tutorial/reflect/
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/
重复 Java 支持可变变量吗?
Java 不支持动态获取基于变量其名称的字符串(也称为变量)。可能有一种不同的方法来完成您想要做的事情,例如使用 Map 对象将名称映射到 bean。如果您编辑问题以更详细地解释您想要做什么,我们可能会得到一些更具体的答案。
(另一方面,如果问题是关于名为 Bean1 的类,那么 Kel 是对的。)
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.)