当前位置: 移动技术网 > IT编程>开发语言>Java > class.forName( )报错

class.forName( )报错

2020年07月17日  | 移动技术网IT编程  | 我要评论

从属性配置文件.properties中读取类名,调用class.forName( )方法获取该类字节码时,发生ClassNotFound错误:
properties文件:

name="Thread.TheThirdThread"

获取字节码并new对象:

FileReader reader = new FileReader("Exercise01/src/Reflect/info.properties");
	Properties pro = new Properties();
	pro.load(reader);
	reader.close();
	String name = pro.getProperty("name");
	Class c = Class.forName(name);
	Object o = c.newInstance();
	System.out.println(o);

发生错误:

Exception in thread "main" java.lang.ClassNotFoundException: "Thread.TheThirdThread"

原因是配置文件中多写了双引号,从而导致取出的类名带双引号,接着引发ClassNotFoundException。将双引号去掉可解决。
properties配置文件:

# 不要加双引号!!!
name=Thread.TheThirdThread

另:class.forName( )方法中一定要填写完整类名(即包名+类名),即便该类与调用forName方法的类在同一包下,也需填写完整类名!

本文地址:https://blog.csdn.net/qq_43183860/article/details/107394649

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网