后加载时期的Java字节码注入

4

我正在尝试钩取Java程序中其他类的方法,我知道这可以在加载时使用Java代理完成。但是,是否有一种方法可以在.class文件加载到JVM后执行,类似于c++中使用Read/Writeprocessmemory()进行dll挂钩?谢谢。


1
请查看此文章:http://theholyjava.wordpress.com/2011/09/07/practical-introduction-into-code-injection-with-aspectj-javassist-and-java-proxy/ - Diego Basch
1个回答

2
如果你是指方法拦截,有两个选项:
1)java.lang.reflect.Proxy。下面的测试为列表创建了一个代理,并拦截其方法调用。注意,它仅适用于接口。
class Handler implements java.lang.reflect.InvocationHandler {
    Object target;

    Handler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before " + method.getName());
        Object res = method.invoke(target, args);
        System.out.println("After " + method.getName());
        return res;
    }
}
List list = new ArrayList();
List proxy = (List) Proxy.newProxyInstance(Test.class.getClassLoader(),
        new Class[] { List.class }, new Handler(list));
proxy.add(1);

打印
Before add
After add

2) 面向切面编程。我认为最简单的入门方法是使用Spring http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接