-1

I have 1 class as mentioned below:

public class mathAdd {

public int add(int val1,int val2) {
    int res = 0;
    res = val1+val2;
    return res;

}

}

I want to pass the method "add" as a parameter something like the way shown in the code below?

public class test4 {

    public static void main(String[] args) {
        test4 t4 = new test4();
        mathAdd m1 = new mathAdd();
        t4.testMeth(m1.add);
    }
    public void testMeth(Object obj.meth()) {

    }

}

Is it possible to do this?? if yes how will I achieve this

azro
  • 53,056
  • 7
  • 34
  • 70
harish cs
  • 1
  • 2
  • What is your real goal ? – azro Feb 13 '19 at 06:30
  • Take a look at interfaces in [`java.util.function` package](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/function/package-summary.html). – Jai Feb 13 '19 at 06:30
  • As like JavaScript and other functional programming languages , we can pass method definition as parameter to another method . This is new feature introduced as part of Java 1.8. – JavaUser Feb 13 '19 at 06:36

2 Answers2

1

You can't do that. A way to pass an existing method as argument is to make the target method itself take a functional interface type, and then you can use a method reference for the method you want to pass as argument:

public void testMeth(IntBinaryOperator method) {
    //IntBinaryOperator defines a method that takes 2 ints and returns an int
    //And that's the signature matching mathAdd#add

    //you can call the method using something like
    int result = method.applyAsInt(int1, int2);
}

And then in main:

public static void main(String[] args) {
    test4 t4 = new test4();
    mathAdd m1 = new mathAdd();

    t4.testMeth(m1::add); //pass the 'add' method
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
-1

this is the return type that you want to pass, and not the method. when you write

t4.testMeth(m1.add());

it will pass return type of the function which is int type, so you need to write testMethod's parameter as,

public void testMeth(int funResult) {

}
Avi Patel
  • 475
  • 6
  • 23