В определенном сценарии вам может потребоваться загрузить некоторые классы, которых нет в вашем пути к классам.
Пример 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/ “, которого нет в пути к классам вашего проекта.
Оригинал: “https://mkyong.com/java/how-to-load-classes-which-are-not-in-your-classpath/”