[英]How to load a class dynamically using classLoader
I have a .class file in disc. 我的光盘中有一个.class文件。 I want to load it dynamically onto jvm using javaassist. 我想使用javaassist将其动态加载到jvm上。 but it throwing exception. 但它抛出异常。 The following is the code i wrote: 以下是我编写的代码:
ClassPath cp=new ClassClassPath(ExampleImpl.class);
System.out.println(cp.find(ExampleImpl.class.getName()));
System.out.println("ExampleImpl.java");
System.out.println(ExampleImpl.class.getName());
System.out.println();
CtClass ctClasz = pool.get("***D:\\ExampleImpl***");
ctClasz.addInterface(pool.get(MyInterface.class.getName()));
There is a .class file on the D: drive and evn it is throwing the following exception: D:驱动器上有一个.class文件,evn引发以下异常:
Exception in thread "main" javassist.NotFoundException: D:\ExampleImpl
at javassist.ClassPool.get(ClassPool.java:436)
at javaassist.Demo.main(Demo.java:24)
How to load a .class file on the disc dynamically onto jvm and execute it??? 如何将光盘上的.class文件动态加载到jvm上并执行它?
Here is something without Eclipse, I think this should work (with minor modifications) 这是没有Eclipse的东西,我认为这应该可以工作(稍作修改)
Class<?> clazz;
try {
clazz = Demo.class.getClassLoader().loadClass("full.package.name.to.MyClass");
} catch (ClassNotFoundException e) {
System.out.println("No such class.");
return;
}
MyInterface worker;
try {
worker = (MyInterface)clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
System.out.println("Error creating actual implementation.");
return;
}
Dynamic Class Loading and Reloading in Java Java中的动态类加载和重新加载
Indeed a great tutorial to learn. 确实是一个很棒的教程。 Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.