Java 重写类实例的方法?

Java 重写类实例的方法?,java,reflection,Java,Reflection,是否可以反射重写类的给定实例的方法 前提条件:游戏有一个可重写的方法act() 公共类Foo{ 公共方法[]getMethods(){ Class s=Game.Class; 返回s.getMethods(); } 公共无效覆盖() { 方法[]arr=getMethods() 对于(int i=0;i如果游戏是一个接口或使用方法act()实现一个接口)您可以使用它。如果接口很小,最优雅的方法可能是使用创建一个类来实现它。不可能使用纯Java动态重写类的方法。您可以创建动态子类。您可能想检查一下

是否可以反射重写类的给定实例的方法

前提条件:游戏有一个可重写的方法
act()

公共类Foo{
公共方法[]getMethods(){
Class s=Game.Class;
返回s.getMethods();
}
公共无效覆盖()
{
方法[]arr=getMethods()

对于(int i=0;i如果游戏是一个接口或使用方法
act()实现一个接口)
您可以使用它。如果接口很小,最优雅的方法可能是使用创建一个类来实现它。

不可能使用纯Java动态重写类的方法。您可以创建动态子类。您可能想检查一下

如果您可以针对接口进行编码,那么您可以使用创建一个代理对象来覆盖该行为,如下例所示。假设
Game
正在实现一个接口
IGame

class GameInvocationHandler implements InvocationHandler
{
    private Game game;
    public GameInvocationHandler(Game game)
    {
        this.game = game;
    }
    Object invoke(Object proxy, Method method, Object[] args)
    {
        if (method.toGenericString().contains("act()")
        {
            //do nothing;
            return null;
        }
        else
        {
            return method.invoke(game, args);
        }
    }
}

Class proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(), IGame.class);
IGame f = (IGame) proxyClass.getConstructor(InvocationHandler.class).newInstance(new Object[] {  });

使用字节码工程和代理可以做类似的事情,除非你真的需要这种黑魔法,只要使用组合和委托就行了。为什么使用本地匿名内部类的方法还不够呢?对实际类进行子类化。从给定的实例动态创建子类会更容易吗该类中的act方法,并处理上一个实例?以前从未这样做过,但这个问题似乎非常有用…期待它的答案..+1从我这边…代码示例?
class GameInvocationHandler implements InvocationHandler
{
    private Game game;
    public GameInvocationHandler(Game game)
    {
        this.game = game;
    }
    Object invoke(Object proxy, Method method, Object[] args)
    {
        if (method.toGenericString().contains("act()")
        {
            //do nothing;
            return null;
        }
        else
        {
            return method.invoke(game, args);
        }
    }
}

Class proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(), IGame.class);
IGame f = (IGame) proxyClass.getConstructor(InvocationHandler.class).newInstance(new Object[] {  });