文章字数:111,阅读全文大约需要1分钟
1.自定义类加载器, 实现findClass
方法。loadClass
在找不到类时会调用此方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class MyClassLoader extends ClassLoader {
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { try{ String filePath = "/Users/zhanjun/Desktop/" + name.replace('.', File.separatorChar) + ".class"; File file = new File(filePath); FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[fis.available()]; fis.read(bytes); Class<?> clazz = this.defineClass(name, bytes, 0, bytes.length); fis.close(); return clazz; }catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally {
} return super.findClass(name); } }
|
- 调用
1 2 3
| public static void main(String[] args) throws Exception { Class clazz0 = new MyClassLoader().loadClass("com.sankuai.discover.memory.OOM"); }
|