ClassLoader.loadClass()方法执行时提示‘ClassNotFoundException’

eclipse中出现‘ClassNotFoundException’错误

在eclipse运行ClassLoader类时,一直出现如下错误

java.lang.ClassNotFoundException: MyTest

出错代码如下:

package work;
class MyTest{
    static {
	System.out.println("静态初始化块....");
    }
}
public class Test {
   
    public static void main(String[] args) throws ClassNotFoundException   {
	ClassLoader cl = ClassLoader.getSystemClassLoader();
	cl.loadClass("MyTest");
	System.out.println("系统加载类");
	Class.forName("MyTest");
    } 
}

 错误原因 :找不到该类

解决办法:在cl.loadClass("MyTest");的MyTest前加入包名,改为如下   cl.loadClass("work.MyTest");

代码改为如下:

package work;
class MyTest{
    static {
	System.out.println("静态初始化块....");
    }
}
public class Test {
   
    public static void main(String[] args) throws ClassNotFoundException   {
	ClassLoader cl = ClassLoader.getSystemClassLoader();
	cl.loadClass("work.MyTest");
	System.out.println("系统加载类");
	Class.forName("work.MyTest");
    } 
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:C马雯娟 返回首页