重写类实例的方法?
是否可以反射性地重写类的给定实例的方法?
前提条件:游戏有一个可重写的方法 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)
}
}
}
}
Is it possible to reflectively override a method for a given instance of a class?
Precondition: Game has an override-able 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)
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 Game 是一个接口或使用
act()
方法实现接口,您可以使用 代理 。如果接口很小,最优雅的方法可能是使用装饰器设计模式创建一个实现它的类。If Game is an interface or implements an interface with the method
act()
you can use Proxy for that. If the interface is small, the most elegant way would probably be to create a class implementing it employing the Decorator design pattern.使用纯 Java 动态重写类的方法是不可能的。 第三方库cglib可以创建动态子类。您可能想检查一下。
如果您可以针对接口进行编码,那么您可以使用 Java动态代理创建一个覆盖行为的代理对象,如下例所示。假设
Game
正在实现接口IGame
。It is not possible to dynamically override methods of a class using pure Java. The third-party library cglib can create dynamic subclasses. You may want to check that out.
If you can code against interface, then you may use Java dynamic proxy to create a proxy object which overrides the behavior, like the example below. Suppose
Game
was implementing an interfaceIGame
.