[英]override a method for an instance of a class?
是否可以反射地覆蓋給定類的實例的方法?
前提條件:游戲具有覆蓋方法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)
}
}
}
}
如果Game是一個接口或使用方法act()
實現接口,則可以使用Proxy 。 如果界面很小,最優雅的方法可能是創建一個使用Decorator設計模式實現它的類。
使用純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[] { });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.