Search code examples
javagenericspolymorphismdynamic-typing

Accepting Objects containing specific method instead of accepting specific Type


[EDIT]: This question is about Types that I have no control over. So making them inherit a superclass or implement an interface is not possible. I want to be able to do this without wrapping the Types.

I would like to write a method that accepts as a parameter all objects that contain a specific method.

For example, we have 2 completely different types that both contain the get method with the same signature:

public class TypeOne {
  public int get() { /* Some implementation */ }
}

public class TypeTwo {
  public int get() { /* Some other implementation */ }
}

How can I write a method that will accept both of these types?

public static int callGetOnObject(GettableObject gettableObject) {
  return gettableObject.get();
}

Solution

  • As far as I know there's no way to actually filter the incoming object by checking if they have a specific method, but you can use reflection to verify input, and then call the function. Here's an example:

     public static void ensureMethodThenCall(Object object, String methodName, Object... args) throws InvocationTargetException, IllegalAccessException{
        Method[] marr = object.getClass().getMethods();
    
        for(Method m: marr){
            if(m.getName().equals(methodName)){
                m.invoke(object, args);
            }
        }
    }