Passing methods as parameters before Java 8

Is it possible to pass methods and parameters? For example, for example:

public int subMethodA(int value1, int value2, int value3){
    int A = value1;
    int B = value2;
    int C = value3;
    return A|B|C;
}

public int subMethodB(int value1, int value2, int value3){
    int A = value1;
    int B = value2;
    int C = value3;
    return A|B|C;
}

and then I have another method in which I want to pass a method parameter;

public void MainMethod(Method mymethod, int value1, int value2, int value3){
    mymethod(value1, value2, value3);
}

So later I can call it using something like:

mainMethod(subMethodA, 1,2,3);
mainMethod(subMethodB, 100,2,1520);

Is it possible?

+4
source share
3 answers

Since you cannot use Java 8, this is what you can do.

Create an interface called Method:

public interface Method {
    public boolean call(int value1,int value2,int value3);
}

Create an implementation of a method called SubMethodA:

public class SubMethodA implements Method {

    @Override
    public boolean call(int value1, int value2, int value3) {
        int A = value1;
        int B = value2;
        int C = value3;
        return A|B|C;//This does not compile
    }

}

Create a main class containing mainMethod:

public class Main {
    public static void mainMethod(Method method,int value1,int value2,int value3) {
        method.call(value1, value2, value3);
    }
}

Now you can call mainMethod as follows:

Main.mainMethod(new SubMethodA(),1,2,3);

- mainMethod, , .java , :

       Main.mainMethod(new Method() {
            public boolean call(int value1, int value2, int value3) {
                int A = value1;
                int B = value2;
                int C = value3;
                return A|B|C;//This does not compile
            }
        },1,2,3);
+4

, , , , , , , , .

, , :

MyClass myInstance = new MyClass();
Method myMethod = MyClass.getMethod("myMethod");
Object myReturn = myMethod.invoke(myInstance,param1,param2,param3);

java.lang.reflect.Method , .

0

No, It is Immpossible. But if you want, you can use a simple design pattern box.

Like this:

class siplmeCrate...{
     int a,b,c;
     public simpleCrate(int a, b..){
          set up abc...
     }

     get abc..

}

Then..

return new simpleCrate(a,b,c);
-1
source

All Articles