簡體   English   中英

我如何創建對象類以執行從Maven存儲庫下載.jar依賴項

[英]How can i create an object class to perform downloading of .jar dependencies from maven repository

根據上面的標題,我需要有關如何創建對象類以執行從maven存儲庫下載.jar依賴項的幫助。 我有一個JAR文件,其中包含三個類,其中包括: CommandHandler.class ; KeyStroke.classMain.class以及每個類都有其依賴項,需要下載免費的Maven存儲庫。 現在,我的問題是如何在我的主程序邏輯開始執行之前,創建一個對象來執行下載依賴項所需的所有必要任務。 因為我相信如果沒有依賴項,我的上述類實現可能會遇到嚴重的異常...請高度贊賞任何幫助/建議/提示。 提前致謝。

如果要在運行時動態加載jar,可以執行以下操作。在下面的示例中,我假設從屬jar是spring-context ,如下所示:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.1.RELEASE</version>
        <scope>provided</scope>
    </dependency>

我得到了那個罐子的URL, http://maven.aliyun.com/nexus/content/groups/public/org/springframework/spring-context/4.3.1.RELEASE/spring-context-4.3.1.RELEASE.jar?spm=0.0.0.0.kG1Pdw&file=spring-context-4.3.1.RELEASE.jar

然后,有一個類Target取決於spring-context包含的DateFormatter類,並且有一個名為start的方法。

import org.springframework.format.datetime.DateFormatter;

public class Target {

private static DateFormatter dateFormatter;

public void start(){
    System.out.println(this.getClass().getClassLoader());
    dateFormatter=new DateFormatter();
    System.out.println(dateFormatter);
    }
}

接下來,我們將上述代碼編譯並打包為一個名為target.jar的jar,並將其存儲在D:\\\\test\\\\target.jar

接下來,我們應該在另一個jar中聲明一個名為BootStrap的類,該類將調用Target實例的方法start BootStarp類將通過同一classloaderURLClassLoader實例)動態加載target.jarspring-context jar文件,因為這樣,在Target實例中start的方法可以訪問spring-context定義的DateFormatter類。

public class BootStrap {


public static void main(String[] args) throws Exception{
    URL url = new URL("http://maven.aliyun.com/nexus/content/groups/public/org/springframework/spring-context/4.3.1.RELEASE/spring-context-4.3.1.RELEASE.jar?spm=0.0.0.0.kG1Pdw&file=spring-context-4.3.1.RELEASE.jar");
    URL url2= (new File("D:\\test\\target.jar").toURI().toURL());
    URLClassLoader classLoader = new URLClassLoader(new URL[]{url,url2});
    Class<?> clz = classLoader.loadClass("com.zhuyiren.Target");
    Object main = clz.newInstance();
    Method test = clz.getMethod("start");
    test.invoke(main);
    }
}

最后,運行BootStrap main方法。有兩點很重要:

  1. BootStrap類和Target類不屬於同一個jar文件。
  2. target.jar未存儲在CLASSPATH路徑中。

我們可以看到結果:

java.net.URLClassLoader@e9e54c2
org.springframework.format.datetime.DateFormatter@4dd8dc3

這樣就可以成功訪問在spring-context jar文件中定義的DateFormatter實例,並且spring-context不存儲在CLASSPATH ,甚至不存儲在本地文件系統中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM