Override method for class instance?

Is it possible to reflexively override a method for a given instance of a class?

Prerequisite: The game has an override method act().

public class Foo {

  public Method[] getMethods() {
    Class s = Game.class;
    return s.getMethods();
  }

  public void override()
  {
    Method[] arr = getMethods()
    for (int i = 0; i<arr.length; i++)
    {
      if (arr[i].toGenericString().contains("act()")
      {
        // code to override method (it can just disable to method for all i care)
      }
    }  
  }                  
}
+5
source share
2 answers

If Game is an interface or implements an interface using a method act(), you can use Proxy . If the interface is small, the most elegant way is probably to create a class that implements it using the Decorator design pattern .

+7
source

Java. cglib . .

, 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[] {  });
+1

All Articles