繁体   English   中英

Java反思:如何在不将另一个项目或JAR添加到我的类路径的情况下从另一个项目加载一个类?

[英]Java reflection: How can I load a class from another project without adding that project or JAR to my classpath?

这是我的情况:我在项目A中有一个类。我想在项目B中的方法中加载该类, 而又不将项目A(或包含该类的JAR)添加到我的项目B类路径中(我个人不反对这样做)这样,但是我必须根据规范进行构建)。

请注意,由于项目A可能安装在不同的位置,因此我将不知道此类的绝对路径(我们称其为“ MyClass”)。 但是,我将知道如何根据当前目录导航到该目录,这就是我所做的。

这是我尝试过的:

// 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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM