Java的自定義類加載器

雙親委派模型:


雙親委派模型.png

實(shí)現(xiàn)自己的類加載器粪滤,并能對(duì)字節(jié)碼實(shí)現(xiàn)加密

import java.io.*;
import java.lang.reflect.*;
public class ShuffleClassLoader extends ClassLoader
{
    private static int mask=0xff;
    private boolean compile(String fileStub) throws IOException
    {
        Process p=Runtime.getRuntime().exec("javac "+fileStub+".java");
        try
        {
            p.waitFor();
        }
        catch (InterruptedException ie)
        {
            System.out.println(ie);
        }
        int ret=p.exitValue();
        if (ret==0)
        {
            File file=new File(fileStub+".class");
            FileInputStream fin=new FileInputStream(file);
            FileOutputStream fout=new FileOutputStream(fileStub+"_sec.class");
            int temp=-1;
            while ((temp=fin.read())!=-1)
            {
                temp=temp^mask;
                fout.write(temp);
            }
            fin.close();
            fout.close();
            file.delete();
            new File(fileStub+"_sec.class").renameTo(file);
        }
        return ret==0;
    }
    private byte[] read(String fileStub) throws IOException
    {
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        try(FileInputStream fin=new FileInputStream(fileStub+".class"))
        {
            int temp=-1;
            while ((temp=fin.read())!=-1)
            {
                temp=temp^mask;
                bos.write(temp);
            }
            return bos.toByteArray();
        }
    }
    protected Class<?> findClass(String name) throws ClassNotFoundException
    {
        Class clazz=null;
        String fileStub=name.replace(".","/");
        String javaFileName=fileStub+".java";
        String classFileName=fileStub+".class";
        File javaFile=new File(javaFileName);
        File classFile=new File(classFileName);
        if (javaFile.exists()&&(!classFile.exists()
            ||javaFile.lastModified()>classFile.lastModified()))
        {
            try
            {
                //調(diào)用compile()方法缎谷,得到.class文件
                if (!compile(fileStub)||!classFile.exists())
                {
                    throw new ClassNotFoundException(javaFileName);
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        if (classFile.exists())
        {
            try
            {
                //調(diào)用read()方法颖变,把二進(jìn)制文件轉(zhuǎn)換為字節(jié)數(shù)組
                byte[] raw=read(fileStub);
                //調(diào)用defineClass()方法掌实,把字節(jié)數(shù)組轉(zhuǎn)換為Class實(shí)例
                clazz=defineClass(name,raw,0,raw.length);
            }
            catch (IOException ie)
            {
                ie.printStackTrace();
            }
        }
        if (clazz==null)
        {
            throw new ClassNotFoundException(name);
        }
        return clazz;
    }
    public static void main(String[] args) throws Exception
    {
        if (args.length<1)
        {
            System.out.println("缺少目標(biāo)類陪蜻,請(qǐng)安如下格式:");
            System.out.println("java ShuffleClassLoader ClassName");
        }
        String progClass=args[0];
        String[] progArgs=new String[args.length-1];
        System.arraycopy(args,1,progArgs,0,progArgs.length);
        ShuffleClassLoader scl=new ShuffleClassLoader();
        Class<?> clazz=scl.findClass(progClass);
        Method main=clazz.getMethod("main",(new String[0]).getClass());
        Object argsArray[]={progArgs};
        main.invoke(null,argsArray);
    }
}

用這個(gè)自定義的類加載器可以編譯源代碼,即.java文件贱鼻,生成.class文件宴卖,而且只能用這個(gè)自定義的類加載器運(yùn)行.class文件。
例如對(duì)于下面的Hello.java

public class Hello 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello World!");
    }
}

輸入java ShuffleClassLoader Hello命令可以得到Hello.class文件邻悬,并輸出"Hello World"症昏。
如果直接輸入 java Hello,輸出如下:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 889275713 in class file Hello
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)

貼一點(diǎn)ClassLoader類的源碼:

    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }
    protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    if (parent != null) {
                        c = parent.loadClass(name, false);
                    } else {
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }

                if (c == null) {
                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();
                    c = findClass(name);

                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        throw new ClassNotFoundException(name);
    }
    protected final Class<?> defineClass(String name, byte[] b, int off, int len)
        throws ClassFormatError
    {
        return defineClass(name, b, off, len, null);
    }
    protected final Class<?> defineClass(String name, byte[] b, int off, int len,
                                         ProtectionDomain protectionDomain)
        throws ClassFormatError
    {
        protectionDomain = preDefineClass(name, protectionDomain);
        String source = defineClassSourceLocation(protectionDomain);
        Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
        postDefineClass(c, protectionDomain);
        return c;
    }
    protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
                                         ProtectionDomain protectionDomain)
        throws ClassFormatError
    {
        int len = b.remaining();

        // Use byte[] if not a direct ByteBufer:
        if (!b.isDirect()) {
            if (b.hasArray()) {
                return defineClass(name, b.array(),
                                   b.position() + b.arrayOffset(), len,
                                   protectionDomain);
            } else {
                // no array, or read-only array
                byte[] tb = new byte[len];
                b.get(tb);  // get bytes out of byte buffer.
                return defineClass(name, tb, 0, len, protectionDomain);
            }
        }

        protectionDomain = preDefineClass(name, protectionDomain);
        String source = defineClassSourceLocation(protectionDomain);
        Class<?> c = defineClass2(name, b, b.position(), len, protectionDomain, source);
        postDefineClass(c, protectionDomain);
        return c;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末父丰,一起剝皮案震驚了整個(gè)濱河市肝谭,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蛾扇,老刑警劉巖攘烛,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異镀首,居然都是意外死亡坟漱,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門更哄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來芋齿,“玉大人,你說我怎么就攤上這事成翩∶倮Γ” “怎么了?”我有些...
    開封第一講書人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵麻敌,是天一觀的道長(zhǎng)栅炒。 經(jīng)常有香客問我,道長(zhǎng)术羔,這世上最難降的妖魔是什么职辅? 我笑而不...
    開封第一講書人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮聂示,結(jié)果婚禮上域携,老公的妹妹穿的比我還像新娘。我一直安慰自己鱼喉,他們只是感情好秀鞭,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開白布趋观。 她就那樣靜靜地躺著,像睡著了一般锋边。 火紅的嫁衣襯著肌膚如雪皱坛。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,475評(píng)論 1 312
  • 那天豆巨,我揣著相機(jī)與錄音剩辟,去河邊找鬼。 笑死往扔,一個(gè)胖子當(dāng)著我的面吹牛贩猎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播萍膛,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼吭服,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了蝗罗?” 一聲冷哼從身側(cè)響起艇棕,我...
    開封第一講書人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎串塑,沒想到半個(gè)月后沼琉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡桩匪,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年打瘪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吸祟。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖桃移,靈堂內(nèi)的尸體忽然破棺而出屋匕,到底是詐尸還是另有隱情,我是刑警寧澤借杰,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布过吻,位于F島的核電站,受9級(jí)特大地震影響蔗衡,放射性物質(zhì)發(fā)生泄漏纤虽。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一绞惦、第九天 我趴在偏房一處隱蔽的房頂上張望逼纸。 院中可真熱鬧,春花似錦济蝉、人聲如沸杰刽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贺嫂。三九已至滓鸠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間第喳,已是汗流浹背糜俗。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留曲饱,地道東北人悠抹。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像渔工,于是被迫代替她去往敵國(guó)和親锌钮。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容