Как загрузить классы, которых нет в вашем classpath
В некоторых случаях вам может потребоваться загрузить некоторые классы, которых нет в вашем пути к классам.
Пример 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/», которого нет в пути к классам вашего проекта.