java字符串到类 [英] java String to class

查看:118
本文介绍了java字符串到类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

您应该使用Java Reflection API:

You should use Java Reflection API:

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

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

Then you may use c.newInstance() to instantiate your class. This method uses constructor which does not require parameters.

请参阅此处的详细信息: http://download.oracle.com/javase/tutorial/reflect/

See details here: http://download.oracle.com/javase/tutorial/reflect/

这篇关于java字符串到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆