簡體   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