在Java中运行时合成新方法? [英] Synthesizing new methods at runtime in Java?

查看:225
本文介绍了在Java中运行时合成新方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java类可以在运行时向自己添加方法吗?

是否可以在运行时为Java中的类合成新方法?是否有可以实现这一目标的库?

Is it possible to synthesize a new method at runtime for a class in Java? Is there a library to make that possible?

推荐答案

除了字节码工程库之外,如果你有一个类的接口,你可以使用Java的代理类。

Beyond bytecode engineering libraries, if you have an interface for your class, you could use Java's Proxy class.

使用界面:

public interface Foo {
    void bar();
}

具体类:

class FooImpl {
    public void bar() {
        System.out.println("foo bar");
    }
}

要处理调用的方法,请使用 InvocationHandler

To process the methods called, you use InvocationHandler:

class FooInvocationHandler implements InvocationHandler {

    private Foo foo;

    FooInvocationHandler(Foo foo) {
        this.foo = foo;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
        if (method.getName().equals("bar"))
            System.out.println("foo me");
            // return null if you don't want to invoke the method below
        }
        return method.invoke(foo, args); // Calls the original method
    }
}

然后创建一个 FooFactory 使用 FooImpl 实例/docs/api/java/lang/reflect/Proxy.html\"rel =nofollow> 代理商

Then create a FooFactory to generate and wrap FooImpl instances using Proxy:

public class FooFactory {
    public static Foo createFoo(...) {
        Foo foo = new FooImpl(...);
        foo = Proxy.newProxyInstance(Foo.class.getClassLoader(),
                new Class[] { Foo.class },
                new FooInvocationHandler(foo));
        return foo;
    }
}

这将包装 FooImpl object以便:

This would wrap the FooImpl object so that this:

Foo foo = FooFactory.createFoo(...);
foo.bar();

打印:

foo me
foo bar

这是BCEL库的替代品,可以做到这一点以及更多,包括从运行时信息生成类,但BCEL库不是本机的。 (代理在1.3以来的所有内容中都在 java.lang.reflect 中。)

This is an alternative to the BCEL libraries, which can do this and a lot more, including generating classes from runtime information, but the BCEL libraries aren't native. (Proxy is in java.lang.reflect on everything since 1.3.)

这篇关于在Java中运行时合成新方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆