加载不在类路径中的类 [英] Loading classes not present in the classpath

查看:167
本文介绍了加载不在类路径中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经使用Groovyc编译了一个Groovy脚本,该脚本在文件系统中生成了一个或多个.class文件。从Java应用程序中,如何将这些类动态添加到类路径中以加载它们并调用它们的方法?目标是预编译Groovy脚本并将它们存储到数据库中,因此可以从编译后的脚本版本执行评估。

您可以创建一个 URLClassLoader 从目录加载新类:

  URL dirUrl =新的URL(file:/+path_to_dir +/); // 1 
URLClassLoader cl = new URLClassLoader(new URL [] {dirUrl},
getClass()。class.getClassLoader()); // 2
Class loadedClass = cl.loadClass(com.xyz.MyClass);
MyClass obj =(MyClass)loadedClass.newInstance();
obj.doSomething();

第1行为目录创建 URL .class文件所在的位置。



第2行创建一个新的 URLClassLoader 实例。第一个参数是一组要用作源的URL。您可以在数组中指定多个目录URL。第二个参数是将成为这个新类加载器的父类的类加载器。我们传递类的类加载器来执行上面的代码作为这个参数。

子类加载器加载的类可以访问父类加载器加载的类。

>

Let's say I've compiled a Groovy script using Groovyc, which has generated one or more .class files in the file system. From a Java application, how do I add those classes to the classpath dynamically in order to load them and call their methods? The goal is to pre-compile Groovy scripts and store them into the database, so evaluation can be performed from compiled versions of the scripts.

解决方案

You can create an instance of URLClassLoader to load new classes from a directory:

URL dirUrl = new URL("file:/" + "path_to_dir" + "/");             // 1
URLClassLoader cl = new URLClassLoader(new URL[] {dirUrl},
                             getClass().class.getClassLoader());  // 2
Class loadedClass = cl.loadClass("com.xyz.MyClass");
MyClass obj = (MyClass) loadedClass.newInstance();
obj.doSomething();

Line 1 creates the URL to the directory where the .class files reside.

Line 2 creates a new URLClassLoader instance. First argument is an array of URLs to be used as the source. You can specify multiple directory URLs within the array. Second argument is the classloader that will become the parent of this new classloader. We pass the classloader of the class executing the above code as this argument.

The classes loaded by a child classloader can access the classes loaded by the parent classloader.

这篇关于加载不在类路径中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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