自定义类加载器
package com.wangbiao.security; public class Boy { public void getBoy(){ System.out.println("上帝是个宝贝"); } public static Object getBoyObject(){ return new Object(); } private static Object getStaticBoyObject(){ return new Object(); } }
package com.wangbiao.security; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; public class MyClassLoader extends ClassLoader { static { System.out.println(">>>>>>>>>>>"); } public String getRoot() { return root; } public void setRoot(String root) { this.root = root; } private String root; @Override protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] classData = getByte(name); if (classData == null) { throw new ClassNotFoundException(); } else { return defineClass(name, classData, 0, classData.length); } } private byte[] getByte(String name) { String fileName = ".\\target\\classes\\com\\wa\\security\\" + name.replace('.', File.separatorChar) + ".class"; FileInputStream fis; try { fis = new FileInputStream(fileName); //自行处理加密解密等逻辑 ByteArrayOutputStream bao = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { bao.write(len); } bao.flush(); return bao.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } }
package com.wangbiao.security; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Test { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { MyClassLoader myClassLoader=new MyClassLoader(); myClassLoader.setRoot("自定义编译路径"); Class<?> aClass = myClassLoader.loadClass("Boy"); Object o = aClass.newInstance(); Method getBoy = aClass.getMethod("getBoy"); getBoy.invoke(o); } }
一点点学习,一丝丝进步。不懈怠,才不会被时代淘汰