Preface
Sometimes the project will use Java to dynamically load the specified class or JAR packet reflection call its method to achieve the separation of modules, so that the coupling between the various functions greatly reduced, more modular, more efficient code. The proxy pattern in the schema is used in the Java mechanism. Let's look at the code below to see how this can be done.
Code details
Package Loadjarclass;import Java.io.file;import Java.lang.reflect.method;import java.net.url;import Java.net.urlclassloader;import Org.junit.test;public class Loadjarclasstest {@Testpublic void Testloadclass () throws exception{/* dynamically loads the specified class */file file=new file ("D:/test");//classpath (upper layer of package file) URL Url=file.touri (). Tourl (); ClassLoader loader=new urlclassloader (New Url[]{url});//Create Class loader//import Com.sun.org.apache.bcel.internal.util.classloader;//classloader ClassLoader = new ClassLoader (New string[]{""});// Class path class<?> cls=loader.loadclass ("Loadjarclass. Testtest ");//load the specified class, be sure to bring the package name of the class object Obj=cls.newinstance ();//Initialize an instance of method Method=cls.getmethod (" Printstring ", String.class,string.class);//method name and corresponding parameter type Object O=method.invoke (obj, "Chen", "leixing");// The call gets the top of the method MethodSystem.out.println (string.valueof (o));//Output "chenleixing"/* Dynamic load Specifies the way a jar package calls one of the classes */file=new file ("D :/test/commons-lang3.jar ");//jar package Path Url=file.touri (). Tourl (); loader=new URLClassLoader (New Url[]{url});// Create the class loader Cls=loader.loadclass ("Org.apache.Commons.lang3.StringUtils ");//load the specified class, be sure to bring the package name of the class Method=cls.getmethod (" center ", String.class,int.class, String.class);//The type of the method name and corresponding parameters O=method.invoke (null, "Chen", integer.valueof (10), "0");//call to get the top method methods (static method, The first parameter can be null) System.out.println (string.valueof (o));//Output "000chen000", "Chen" string with 3 "0" strings on each side}}
If you are interested in Stringsutils tool class friends, you can refer to my blog: StringUtils method of the complete introduction, Commons-lang common methods
Reflection and agent technical knowledge, can refer to my blog: static agent of Java, dynamic agent, Cglib dynamic agent, using dynamic proxy AOP-based ASPECTJ framework-comparison and detailed, Java reflection mechanism in-depth study
Java dynamically loads the specified class or JAR package reflection calls its method