public class MyClassLoader extends ClassLoader { private String classDir;//自定义类加载器 所查找的目录 MyClassLoader(String classDir){ this.classDir = classDir; } @Override@SuppressWarnings("deprecation") //findClass的主要作用就是 把class文件读取到内存中 那么涉及两个流,,但是class文件被加密 所以需要先解密 然后写入内存 protected Class<?> findClass(String name) throws ClassNotFoundException { String classPath = classDir+"\\"+name+".class"; System.out.println(classPath); try { System.out.println("我的类加载器"); //读取class文件的流 FileInputStream in = new FileInputStream(classPath); //将class文件的二进制数据 写入内存的流 之前要先解密 ByteArrayOutputStream bout = new ByteArrayOutputStream(); //解密 encryption(in, bout); in.close(); byte[] buf = bout.toByteArray(); return defineClass(buf, 0, buf.length);//将一个 byte 数组转换为 Class 类的实例 } catch (Exception e) { // TODO: handle exception e.printStackTrace();; } return super.findClass(name); } public static void main(String[] args) throws Exception { //源class文件路径 // String srcPath = args[0]; String srcPath = "bin/类加载器/testClass.class"; File src = new File(srcPath); // String desDir = args[1];//加密后的class文件存放的目录 String desDir = "bin/333"; //读取指定文件 FileInputStream in = new FileInputStream(src); String desPath = desDir+"\\"+src.getName(); //class文件加密 OutputStream out = new FileOutputStream(desPath); encryption(in,out); System.out.println("class文件加密成功"); } //文件加密代码 从字节输入流in获取文件 进过加密 将数据 写入到输出流 注意 这里不要思维定势 认为 将数据写入OutputStream输出流就是写入文件 private static void encryption(InputStream in,OutputStream out) throws Exception { // TODO Auto-generated method stub int i = -1; while ((i=in.read())!=-1) { out.write(i^0xfff);//将加密的字节数据写入到out流中 // out.write(i);//不加密 } System.out.println("......"); } }
自定义泪价值器2——加密class文件 解密加载class文件
原创
©著作权归作者所有:来自51CTO博客作者倁之的原创作品,请联系作者获取转载授权,否则将追究法律责任
下一篇:自定义注释--
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
使用自定义类加载器加载class
操作流程都在代码注释中: /** * 自定义文件系统类加载器 ---->使用自定义类加
java 加载 System