Scene:
Put the class files and jars in the project into the D:\loader\terry\codex directory, how to get the project to load and use these classes in code way.
Scenario: Using URLClassLoader constructs D:\loader\terry\codex the class loader under this path, and uses these classes to instantiate through the Java reflection mechanism
Example:
Helloworld.java:
Package terry.codex;
/**
* @ Writer: Yh.zeng
* @ Write Time: 2017-12-3 pm 2:29:57
* @ file Description: Todo/
public
class HelloWorld {
public void SayHello () {
System.out.println ("HelloWorld. ");
}
}
Test.java:
Import Java.io.File;
Import Java.lang.reflect.Method;
Import Java.net.URL;
Import Java.net.URLClassLoader;
/**
* @ Writer: Yh.zeng
* @ Write Time: 2017-12-3 pm 2:26:59
* @ file Description: Todo/
public
class Test {
public static void Main (string args[]) {
string fileurlstring = new File ("D:\\loader"). Touri (). toString ();
fileurlstring = Fileurlstring.replaceall ("!/", "%21/");
try {
ClassLoader ClassLoader = new URLClassLoader (new Url[]{new URL (fileurlstring)});
Class Helloworldclazz = Classloader.loadclass ("Terry.codex.HelloWorld");
Object HelloWorld = Helloworldclazz.newinstance ();
Method method = Helloworld.getclass (). GetMethod ("SayHello", null);
Method.invoke (HelloWorld, null);
catch (Exception E1) {
//TODO auto-generated catch block
e1.printstacktrace ();
}
}
}
Demo See: Https://github.com/zengyh/CodeLibary/blob/master/src/clazzloader/UrlClassLoaderTest.java