標籤:system contains method col end 代碼 catch object row
前言
要實現classLoader動態解密class檔案,就必須先瞭解Java的類載入機制、瞭解雙親委託機制。然後自訂一個classLoader,繼承於classLoader。
文章中引用到上一篇文章中的解密方法(edCipher.decryptClass(name)),詳情請移步至:Java加解密Class檔案
代碼實現
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 @Override15 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 @Override23 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 }
Java實現自訂classLoader動態解密class檔案