簡體   English   中英

使用Java Reflection從類路徑中加載類

[英]loading a class from out of classpath by using Java Reflection

我想加載類不在類路徑中的類。 有沒有辦法按文件路徑加載類而不在classpath中? 例如

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

這里取的例子:

// 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) {
}

將類內容加載到字節數組中,並手動使用ClassLoader.html#defineClass(java.lang.String,byte [],int,int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM