loading a class from out of classpath by using Java Reflection

十年热恋 提交于 2019-12-10 18:00:44

问题


I want to load class from that is not in class path. is there any way that I load class by file path without being in classpath ? for example

ClassLoader.load("c:\MyClass.class");

回答1:


Example taken from here:

// Create a File object on the root of the directory containing the class file  
File file = new File("c:\\myclasses\\");

try {
    // Convert File to a URL
    URL url = file.toURL();          // file:/c:/myclasses/
    URL[] urls = new URL[]{url};

    // Create a new class loader with the directory
    ClassLoader cl = new URLClassLoader(urls);

    // Load in the class; MyClass.class should be located in
    // the directory file:/c:/myclasses/com/mycompany
    Class cls = cl.loadClass("com.mycompany.MyClass");
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}



回答2:


Load your class content into a byte array and use ClassLoader.html#defineClass(java.lang.String, byte[], int, int) manually.



来源:https://stackoverflow.com/questions/5926144/loading-a-class-from-out-of-classpath-by-using-java-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!