Java實現自訂classLoader動態解密class檔案

來源:互聯網
上載者:User

標籤: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檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.