Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override a method for an instance of a class?

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)
      }
    }  
  }                  
}
like image 620
Maxwell Dergosits Avatar asked Nov 24 '11 17:11

Maxwell Dergosits


People also ask

Can you override an instance method?

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.

Can you override a method in the same class?

Therefore, you cannot override two methods that exist in the same class, you can just overload them.

How do you override a class method?

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.

Why would you override a method of a base class?

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.


1 Answers

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.

like image 76
Adam Zalcman Avatar answered Oct 20 '22 00:10

Adam Zalcman