개발/Java
자바 시스템 클래스 들을 ASM으로 변경하는법
semtax
2020. 1. 7. 21:14
반응형
자바 시스템 클래스 들을 ASM으로 변경하는법
아래와 같이 자기가 직접 정의된 클래스 로더를 만들어서 수행하면 된다.
대충 순서는 다음과 같다.
- ClassLoader와 Class 클래스를 이용해서 변경하려는 클래스를 읽어 옴
- setAccessible함수를 이용해서 권한을 수정가능한 상태로 변경함
- reflection을 이용해서 ClassLoader.defineClass 을 호출하여 변경하려는 클래스에 접근
- 접근한 클래스를 변경후 반환
아래는 예제 코드이다.
private Class loadClass(byte[] b) {
// Override defineClass (as it is protected) and define the class.
Class clazz = null;
try {
ClassLoader loader = ClassLoader.getSystemClassLoader();
Class cls = Class.forName("java.lang.ClassLoader");
java.lang.reflect.Method method =
cls.getDeclaredMethod("defineClass", new Class[] {
String.class, byte[].class, int.class, int.class });
// Protected method invocation.
method.setAccessible(true);
try {
Object[] args =
new Object[] { className, b, new Integer(0), new Integer(b.length)};
clazz = (Class) method.invoke(loader, args);
} finally {
method.setAccessible(false);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return clazz;
}
출처 : Asm 공식문서 FAQ
반응형