Objective
To implement ClassLoader dynamic decryption class file, we must first understand the Java class loading mechanism and understand the parental delegation mechanism. Then customize a classloader that inherits from the ClassLoader.
The article refers to the decryption method (Edcipher.decryptclass (name)) in the previous article, please go to: Java Plus decrypt class file
Code implementation
1 /**2 * Dynamic Load class3 */4 Public classEdclassloaderextendsClassLoader {5 6 PrivateString toolfile = "Com.pub.Secretive";7 8 PrivateEdcipher Edcipher =NewEdcipher ();9 Ten PublicEdclassloader () { One Super(Thread.CurrentThread (). Getcontextclassloader ()); A } - - @Override the protectedClass<?> Findclass (String name)throwsClassNotFoundException { -Edcipher Edcipher = This. Edcipher = =NULL?NewEdcipher (): This. Edcipher; - byte[] data =Edcipher.decryptclass (name); - intLength = data = =NULL? 0: data.length; + returnDefineClass (toolfile, data, 0, length); - } + A @Override at PublicClass<?> LoadClass (String s)throwsClassNotFoundException { - if(!s.contains ("Checker")) { -Class Loadedclass =Findloadedclass (s); - if(Loadedclass = =NULL) { -Loadedclass =getParent (). LoadClass (s); - returnLoadedclass; in}Else { - returnLoadedclass; to } + } - returnFindclass (s); the } * $ /**Panax Notoginseng * Get classes that need to be decrypted - */ the PublicString Gettoolfile () { + returnToolfile; A } the + //after the class file is loaded dynamically, it needs to be reflected to invoke the method - Public Static voidMain (string[] args)throwsClassNotFoundException { $Edclassloader Edclassloader =NewEdclassloader (); $Object result =NULL; - Try { -Class MyClass =Edclassloader.loadclass (Edclassloader.gettoolfile ()); the //Method1 is the method name . -method = Myclass.getdeclaredmethod ("Method1");WuyiObject obj =myclass.newinstance (); the //result is the method return value -result =Method.invoke (obj); Wu}Catch(Exception e) { - e.printstacktrace (); About } $ System.out.println (result); - } -}
Java implementation Custom ClassLoader dynamic decryption class file