0

I am trying to implement this code:

 public void ActionTypeOne {

   doSomething(ActionType1A action) { ... }
   doSomething(ActionType1B action) { ... }

  }

...

   public void register(Action action) {

        if (action.getClass().equals(ActionType1A) || action.getClass().equals(ActionType1b)) {
            ActionTypeOne.doSomething(action);
        }

   }

Since ActionTypeOne does not implement doSomething(Action), but only doSomething(ActionType1A) and doSomething(ActionType1B), this code will not compile.

However, I know that my object is definitely one of those types because of the code beforehand. I could split this up and cast explicitly to one of my two ActionTypes, but that is messy.

Can I force the line:

ActionTypeOne.doSomething(action) 

to call the correct method in ActionTypeOne based on the class of action?

Jeremy
  • 5,365
  • 14
  • 51
  • 80

2 Answers2

1

You have to explicitly (down)cast depending on the class you are sure your object is instanciated from:

public void register(Action action) {
    if (action instanceof ActionType1A) {
        ActionTypeOne.doSomething((ActionType1A) action);
    } else if (action instanceof ActionType1B) {
        ActionTypeOne.doSomething((ActionType1B) action);
    }
}
ngasull
  • 4,206
  • 1
  • 22
  • 36
1

You could use reflection to get those methods then invoke them.

Approx Code :

//in class init or static
Class []params1 = new Class {ActionType1A};
Method doSomethingActionType1A = ActionTypeOne.class.getDeclaredMethod("doSomething", params1);

//...etc // if you had more than 3 you could add them to hash map to get the correct method based on class name

//when you need to call - get the method via if or hash table and then invoke it

method1.invoke(Object obj, Object... args);

This would work as invoke only checks at run time of the actual object is of the correct type. but code will be slightly slower. not an issue unless you care for a few CPU cycles or have 1,000s of calls

tgkprog
  • 4,493
  • 4
  • 41
  • 70