menteith
menteith

Reputation: 678

Generic call a method in different classes, but with the same method signature

Say there are two classes Foo and Bar. They don't extend the same class (except for the Object class) or implement the same interface. However, both of them have a method with the same signature. These classes are not mine; they cannot be changed. Is there a way to use some kind of generic call for method meth as if these two classes extended the same class or implemented the same interface?

class Foo {

    public void meth(String s) {
    }
}

class Bar {

    public void meth(String s) {
    }
}

Upvotes: 2

Views: 1544

Answers (2)

Swapnil
Swapnil

Reputation: 2502

You can use reflection, but not type safe. depending on Object run time you can call specific method.

import java.lang.reflect.Method; 

try 
    {
        Object f1 = new Foo();
        Object f2 = new Bar();

        Class c1 = f1.getClass();
        Class[] param = new Class[1];   
        param[0] = String.class;
        Method method;
        method = c1.getDeclaredMethod("meth", param);
        method.invoke(f1, "$$$$$$$$$$$$$$");

    } catch (NoSuchMethodException | SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 1

khelwood
khelwood

Reputation: 59112

In Java 8 or later you can use method references.

Foo myFoo = ...;
Bar myBar = ...;

Consumer<String> fn1 = myFoo::meth;
Consumer<String> fn2 = myBar::meth;

Pass the appropriate Consumer<String> to the place where you want the method called.

Consumer<String> is appropriate for a method with one string argument and no return type. If your method signatures were different, there are lots of other functional interfaces that might match better.

Given a Consumer<String> fn, you can call the referenced method with fn.accept("abc").

Upvotes: 1

Related Questions