使用Java Reflection从类路径中加载类

ref*_*tor 4 java reflection classpath

我想加载类不在类路径中的类.有没有办法按文件路径加载类而不在classpath中?例如

ClassLoader.load("c:\MyClass.class");
Run Code Online (Sandbox Code Playgroud)

Pet*_*ego 7

这里取的例子:

// 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) {
}
Run Code Online (Sandbox Code Playgroud)