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)
}
}
}
}
3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors.
Therefore, you cannot override two methods that exist in the same class, you can just overload them.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.
The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With