欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

class.forName( )报错

程序员文章站 2022-06-21 13:44:40
从属性配置文件.properties中读取类名,调用class.forName( )方法获取该类字节码时,发生ClassNotFound错误:properties文件:name="Thread.TheThirdThread"获取字节码并new对象:FileReader reader = new FileReader("Exercise01/src/Reflect/info.properties");Properties pro = new Properties();pro.load(rea...

从属性配置文件.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

相关标签: Java基础语法