A full read of the Java Virtual machine in depth in the coming period
Here to remember the online see a few introduction class loader article, and so read to the virtual machine class loading mechanism is described in detail.
ClassLoader in Hyper-detailed Java
Deep understanding of the Java class loader
Post a class loader of your own writing.
Hello class. Put the compiled class file under a different path.
Package ww; Public class Hello { publicvoid say () { System. out. println ("helloWorld");} }
Wwclassloader class. Inheriting the ClassLoader class overriding the Findclass () method
Package Ww;import Java.io.bytearrayoutputstream;import java.io.file;import java.io.fileinputstream;import java.io.FileNotFoundException; Public classWwclassloader extends ClassLoader {PrivateString path;//Path PublicWwclassloader (String path) { This. Path =path; } @OverrideprotectedClass<?>Findclass (string name) throws ClassNotFoundException {string FileName=parsefilename (name); File File=NewFile (path,filename); Try { //Read class fileFileInputStream FIS =Newfileinputstream (file); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); intLenth =0; while((Lenth = Fis.read ())! =-1) {baos.write (lenth); } byte[] buffer =Baos.tobytearray (); Baos.close (); Fis.close (); //instantiating a Class object returnDefineClass (Name,buffer,0, buffer.length); } Catch(Exception e) {e.printstacktrace (); } returnSuper.findclass (name); } //Parse File path Privatestring Parsefilename (string name) {intindex = Name.lastindexof ('.'); if(Index = =-1) { returnname+". Class"; } Else { returnName.substring (index+1)+". Class"; } }}
Wwtest class. Call Test
Package Ww;import Java.lang.reflect.Method; Public classWwtest { Public Static voidMain (string[] args) {//I've been looking for it. The parent node of the class you define must be the source code for the Appclassloader class. If you know the big guy, you can tell me. /*private static native void Registernatives (); static {registernatives (); }*/wwclassloader ww=NewWwclassloader ("E://lib"); Try{Class hel= Ww.findclass ("ww. Hello"); //Reflection Execution Method if(Hel! =NULL) {Object obj=hel.newinstance (); Method Method= Hel.getdeclaredmethod ("say",NULL); Method.invoke (obj,NULL); } } Catch(Exception e) {e.printstacktrace (); } }}
Java Class Loader Learning notes