Java反射:如何从另一个项目加载一个类而不将该项目或JAR添加到我的类路径?

Java反射:如何从另一个项目加载一个类而不将该项目或JAR添加到我的类路径?,java,reflection,classloader,classnotfoundexception,urlclassloader,Java,Reflection,Classloader,Classnotfoundexception,Urlclassloader,我的情况如下: 我在项目a中有一个类。我想在项目B的方法中加载这个类,而不将项目a(或包含该类的JAR)添加到我的项目B类路径中(我个人不反对这样做,但我必须按照规范构建它) 注意,我不知道这个类的绝对路径(我们称之为“MyClass”),因为项目A可能安装在不同的位置。然而,我将知道如何根据我当前的目录导航到它,所以这就是我所做的 以下是我尝试过的: // Navigate to the directory that contains the class File pwd = new File

我的情况如下: 我在项目a中有一个类。我想在项目B的方法中加载这个类,而不将项目a(或包含该类的JAR)添加到我的项目B类路径中(我个人不反对这样做,但我必须按照规范构建它)

注意,我不知道这个类的绝对路径(我们称之为“MyClass”),因为项目A可能安装在不同的位置。然而,我将知道如何根据我当前的目录导航到它,所以这就是我所做的

以下是我尝试过的:

// 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) {
}

这会引发ClassNotFoundException。我做错什么了吗?

您需要实现一个自定义类加载器,类似这样的东西

    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");
Class cls=new ClassLoader(){
public java.lang.Class loadClass(字符串名称)引发ClassNotFoundException{
byte[]a=从已知位置读取类字节
返回defineClass(名称,b,0,a.长度);
};
}.loadClass(“test.MyClass”);

首先,.class文件真的在您的src/文件夹中吗?您的“dir”文件当前指向一个src/文件夹。请注意:
新文件(src.getAbsolutePath()+file.separator+“folder”+file.separator+“src”)
可以简化为:
新文件(src,“folder/src”)
我这样做
文件文件=新文件(dirPath+filineName);URL URL=file.getCanonicalFile().toURI().toURL();URLClassLoader classLoader=新URLClassLoader(新URL[]{URL})和dirPath的获取方式如下
字符串dirPath=System.getProperty(“user.dir”)+File.separator+JAR\u dir+File.separator