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

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

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

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.example.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/」からロードされていることがわかります。