Java示例与ClassLoader [英] Java example with ClassLoader

查看:105
本文介绍了Java示例与ClassLoader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有小问题.我学习Java SE并找到ClassLoader类.我尝试在下面的代码中使用它: 我正在尝试使用URLClassLoader在运行时动态加载类.

I have small problem. I learn java SE and find class ClassLoader. I try to use it in below code: I am trying to use URLClassLoader to dynamically load a class at runtime.

URLClassLoader urlcl = new URLClassLoader(new URL[] {new URL("file:///I:/Studia/PW/Sem6/_repozytorium/workspace/Test/testJavaLoader.jar")});
Class<?> classS = urlcl.loadClass("michal.collection.Stack");
for(Method field: classS.getMethods()) {
     System.out.println(field.getName());
}
Object object = classS.newInstance();
michal.collection.Stack new_name = (michal.collection.Stack) object;

java虚拟机看不到我的课程,并且出现以下异常:

The java virtual machine does not see me class, and I get the following exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: michal cannot be resolved to a type michal cannot be resolved to a type at Main.main(Main.java:62)

您知道我如何解决此问题吗?

推荐答案

Class<?> classS = urlcl.loadClass("michal.collection.Stack");
[...]
Object object = classS.newInstance();
michal.collection.Stack new_name = (michal.collection.Stack) object;

因此,您尝试动态加载类,然后静态引用它.如果您已经可以静态链接到它,则说明已加载并且无法再次加载.您需要通过反射访问方法.

So you're attempting to dynamically load a class and then you statically refer to it. If you can already statically link to it, then its loaded and you can't load it again. You'll need to access the methods by reflection.

您通常要做的是让加载的类实现父类加载器的接口.创建一个实例(通常只是一个实例)后,您可以通过带有接口类型的引用来引用它.

What you would usually do is have the loaded class implement an interface from the parent class loader. After an instance is created (usually just a single instance), then you can refer to it through a reference with a type of the interface.

public interface Stack {
   [...]
}
[...]
    URLClassLoader urlcl = URLClassLoader.newInstance(new URL[] {
       new URL(
           "file:///I:/Studia/PW/Sem6/_repozytorium/workspace/Test/testJavaLoader.jar"
       )
    });
    Class<?> clazz = urlcl.loadClass("michal.collection.StackImpl");
    Class<? extends Stack> stackClass = clazz.asSubclass(Stack.class);
    Constructor<? extends Stack> ctor = stackClass.getConstructor();
    Stack stack = ctor.newInstance();

(通常,堆栈溢出免责声明不如编译.)

(Usual Stack Overflow disclaimer about not so much as compiling.)

您需要添加错误处理才能品尝. URLClassLoader.newInstanceURLClassLoader添加了一些改进. Class.newInstance已完全打破异常处理,应避免使用.

You'll need to add error handling to taste. URLClassLoader.newInstance adds a bit of refinement to URLClassLoader. Class.newInstance has completely broken exception handling and should be avoided.

这篇关于Java示例与ClassLoader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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