微信扫一扫

028-83195727 , 15928970361
business@forhy.com

将16进制文本加载成类(写着玩的,所以很多方面看着不顺眼)

2016-05-27

package test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MyClassLoader extends ClassLoader{
    
    @Override
    public Class<?> findClass(String className) throws ClassNotFoundException{
        String path = "C:\\Users\\mgsd\\Desktop\\"+className.replace(".", File.separator)+".txt";
        try {
            byte[] bts = Files.readAllBytes(Paths.get(path));
            String s = new String(bts);
            s = s.replaceAll("\n", " ");
            s = s.replaceAll("\\s+", " ");
            String str[] = s.split(" ");
            byte[] newbyte = new byte[str.length];
            for(int i=0,len=str.length;i<len;i++){
                String s1 = str[i];
                if(s1.length()!=2) continue;
                String h = Integer.toBinaryString(Integer.parseInt(s1.substring(0,1) , 16));
                while(h.length()<4){
                    h = "0"+h;
                }
                String l = Integer.toBinaryString(Integer.parseInt(s1.substring(1), 16));
                while(l.length()<4){
                    l = "0"+l;
                }
                byte b = Byte.parseByte(h.substring(1)+l, 2);
                if("1".equals(h.substring(0, 1))){
                    b = (byte)(b-128);
                }
                newbyte[i] = b;
            }
            Class<?> clazz = defineClass(className, newbyte, 0, newbyte.length);
            if(clazz==null) throw new ClassNotFoundException(className);
            return clazz;
        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException(className);
        }
    }
}