開発者ドキュメント

クラスパスにないクラスをロードする方法

特定のシナリオでは、クラスパスにないクラスをロードする必要があります。

Javaの例

フォルダ ”

c:\\ other__classes \\

“がプロジェクトのクラスパスにないと仮定して、このフォルダからJavaクラスをロードする方法を示す例を次に示します。コードとコメントは自明です。

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;

public class App{

    public static void main(String[]args) {

    try{

        File file = new File("c:\\other__classes\\");

               //convert the file to URL format
        URL url = file.toURI().toURL();
        URL[]urls = new URL[]{url};

               //load this folder into Class loader
        ClassLoader cl = new URLClassLoader(urls);

               //load the Address class in 'c:\\other__classes\\'
        Class  cls = cl.loadClass("com.mkyong.io.Address");

               //print the location from where this class was loaded
        ProtectionDomain pDomain = cls.getProtectionDomain();
        CodeSource cSource = pDomain.getCodeSource();
        URL urlfrom = cSource.getLocation();
        System.out.println(urlfrom.getFile());

    }catch(Exception ex){
        ex.printStackTrace();
    }
  }
}

出力

…​./c:/other__classes/…​.

このクラスは、プロジェクトクラスパスにない ”

/c:/other__classes/

“から読み込まれます。

モバイルバージョンを終了