要實現classLoader動態解密class文件,就必須先了解Java的類加載機制、瞭解雙親委託機制。而後自定義一個classLoader,繼承於classLoader。html
文章中引用到上一篇文章中的解密方法(edCipher.decryptClass(name)),詳情請移步至:Java加解密Class文件ide
1 /** 2 * 動態加載類 3 */ 4 public class EdClassLoader extends ClassLoader { 5 6 private String toolFile = "com.pub.Secretive"; 7 8 private EdCipher edCipher = new EdCipher(); 9 10 public EdClassLoader() { 11 super(Thread.currentThread().getContextClassLoader()); 12 } 13 14 @Override 15 protected Class<?> findClass(String name) throws ClassNotFoundException { 16 EdCipher edCipher = this.edCipher == null ? new EdCipher() : this.edCipher; 17 byte[] data = edCipher.decryptClass(name); 18 int length = data == null ? 0 : data.length; 19 return defineClass(toolFile, data, 0, length); 20 } 21 22 @Override 23 public Class<?> loadClass(String s) throws ClassNotFoundException { 24 if (!s.contains("Checker")) { 25 Class loadedClass = findLoadedClass(s); 26 if (loadedClass == null) { 27 loadedClass = getParent().loadClass(s); 28 return loadedClass; 29 } else { 30 return loadedClass; 31 } 32 } 33 return findClass(s); 34 } 35 36 /** 37 * 獲取須要解密的類 38 */ 39 public String getToolfile() { 40 return toolFile; 41 } 42 43 //在動態加載class文件後,須要經過反射才能調用其中方法 44 public static void main(String[] args) throws ClassNotFoundException { 45 EdClassLoader edClassLoader = new EdClassLoader(); 46 Object result = null; 47 try { 48 Class myClass = edClassLoader.loadClass(edClassLoader.getToolfile()); 49 // method1 就是方法名 50 Method method = myClass.getDeclaredMethod("method1"); 51 Object obj = myClass.newInstance(); 52 // result 就是方法返回值 53 result = method.invoke(obj); 54 } catch (Exception e) { 55 e.printStackTrace(); 56 } 57 System.out.println(result); 58 } 59 }