如何在java中将String类型转换为Class类型 [英] How to convert String type to Class type in java

查看:820
本文介绍了如何在java中将String类型转换为Class类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在包中打印所有类名,并在每个包中打印相应的属性及其数据类型。

I want to print all the class names in a package and also to print the corresponding attributes and their data types in each package.

在一个代码中,我是能够以字符串的形式获取类名。
在另一个代码中,我能够使用 Classname.class.getAttribute();

In one code, I am able to get the classnames in the form of string. In another code I am able to get the attributes and their data types using Classname.class.getAttribute();

但是我想合并这两个代码。因为在第一个代码中我得到了字符串形式的类名,所以我不能使用 Classname.class.getAttribute(),因为这里 Classname 的类型为 String

However I want to merge the two codes. Since in the first code I got the classnames in the form of string , I can't use Classname.class.getAttribute() since here Classname will be of type String.

所以我想要一个方法来转换 Classnamefrom String type to Class type。

So I want a method which will convert the "Classname" from String type to Class type.

我尝试了 Class.forName()但它没有用。

推荐答案

Class<?> classType = Class.forName(className);

确保 className 是完全限定的类名喜欢 com.package.class 另外,请分享您看到的错误消息。

Make sure className is fully qualified class name like com.package.class Also, please share your error message that you see.

这篇关于如何在java中将String类型转换为Class类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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