[英]Java reflection: How can I load a class from another project without adding that project or JAR to my classpath?
Here's my situation: I have a class in project A. I want to load this class in a method in project B without adding project A (or a JAR containing the class) to my project B classpath (I personally have no objection to doing it that way, but I must build this to spec). 这是我的情况:我在项目A中有一个类。我想在项目B中的方法中加载该类, 而又不将项目A(或包含该类的JAR)添加到我的项目B类路径中(我个人不反对这样做)这样,但是我必须根据规范进行构建)。
Note that I will not know the absolute path to this class (let's call it "MyClass") as project A may be installed various different locations. 请注意,由于项目A可能安装在不同的位置,因此我将不知道此类的绝对路径(我们称其为“ MyClass”)。 I will, however, know how to navigate to it based on my current directory, so that is what I have done.
但是,我将知道如何根据当前目录导航到该目录,这就是我所做的。
Here is what I have tried: 这是我尝试过的:
// Navigate to the directory that contains the class
File pwd = new File(System.getProperty("user.dir"));
File src = pwd.getAbsoluteFile().getParentFile();
File dir = new File(src.getAbsolutePath() + File.separator + "folder" + File.separator + "src");
// dir is the directory that contains all the packages of project A
// Load the class
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {dir.toURI().toURL()});
try {
classLoader.loadClass("com.blahblahblah.MyClass");
} catch (ClassNotFoundException exception) {
}
This throws a ClassNotFoundException. 这将引发ClassNotFoundException。 Am I doing something wrong?
难道我做错了什么?
You need to implement a custom classloader, something like this 您需要实现一个自定义的类加载器,类似这样
Class<?> cls = new ClassLoader() {
public java.lang.Class<?> loadClass(String name) throws ClassNotFoundException {
byte[] a = read class bytes from known location
return defineClass(name, b, 0, a.length);
};
}.loadClass("test.MyClass");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.