在Java中将方法作为参数传递给另一个方法

huangapple go评论101阅读模式
英文:

Passing method as parameter to another method in Java

问题

class A {

    doSameThingA(int x) {
        // 使用x进行相同操作
        methodA();
    }

    doSameThingB(int x) {
        // 使用x进行相同操作
        methodB();
    }

    doSameThingC(int x) {
        // 使用x进行相同操作
        methodC();
    }

    // 我想要写一个单一的函数来替代上面的三个函数
    doSameThing(int x, Method method) {
        // 使用x进行相同操作
        method.invoke(this);
    }
}
英文:

I have 3 methods which does the same thing but at the end the 3 methods call a diff method. So instead of having 3 methods, I want to have a single method which will accept a method as parameter which it will call at the end

How can I do this please, I tried having a look at the java reflection that did not work, Not sure if interfaces is the right way for this.

please suggest
Thanks
R

class A {

doSameThingA(int x) {
 //do same thing with x
 methodA()
}
doSameThingB(int x) {
 //do same thing with x
 methodB()
}

doSameThingC(int x) {
 //do same thing with x
 methodC()
}

//I WANT TO WRITE A SINGLE FUNCTION replacing the above three
doSameThing(int x, Method method) {
//do same thing with x
method()
}
} 

答案1

得分: 1

在Java中存在一个被称为双冒号操作符的运算符。它也被称为方法引用操作符,因为它引用方法。我相信这个特性将允许您通过对方法进行参数化来解决问题,有点类似于Lambda表达式。

class A {
    public static void main(String... args) {
        new A().doSameThing(1, MethodClass::printSomething);
    }

    void doSameThing(int x, Runnable method) {
        method.run();
    }
} 

class MethodClass {
    public static void printSomething() {
        System.out.println("Hello World");
    }
}

上面是一个示例。MethodClass 包含了您想要运行的方法(例如 methodA()、methodB()、methodC() 等)。doSameThing 方法接受一个 Runnable,这是一个不接受参数且不返回值的函数式接口。通过传递不接受参数且不返回值的 printSomething 方法,我们可以在 doSameThing 方法内运行该方法。

当然,您使用的函数式接口类型将取决于您的方法的设计目的。

此外,如果您的其他方法(methodA()、methodB() 等)在代码中没有其他地方使用,您可以使用匿名类直接在现场实现 Runnable 接口。以下是上述示例以该形式编写的版本:

class A {
    public static void main(String... args) {
        new A().doSameThing(1, new Runnable() {
            public void run() {
                System.out.println("Hello World");
            }
        });
    }
    
    void doSameThing(int x, Runnable method) {
        method.run();
    }
}

由于 Runnable 是一个函数式接口,您甚至可以使用 Lambda 表达式来实现。

class A {
    public static void main(String... args) {
        new A().doSameThing(1, () -> {    
            System.out.println("Hello World");
        });
    }
    
    void doSameThing(int x, Runnable method) {
        method.run();
    }
}
英文:

An operator exists in java known as the double colon operator. It is also known as the method reference operator because it refers to methods and this feature I believe will allow you to solve your problem by parameterizing your method. Kind of like lambdas.

class A {
    public static void main(String... args) {
        new A().doSameThing(1, MethodClass::printSomething);
    }

    void doSameThing(int x, Runnable method) {
        method.run();
    }
} 

class MethodClass {
    public static void printSomething() {
        System.out.println("Hello World");
    }
}

The above is an example. MethodClass contains the method you want to run (such as your methodA(), methodB(), methodC(), and so forth. The doSameThing method takes in a Runnable, which is a functional interface that takes no parameters and returns no value. By passing the method printSomething, which takes no parameters and returns no value, we can run that method within the doSameThing method.

Of course, the type of functional interface you use would depend on what your methods are designed to accomplish.

Furthermore, if your other methods (methodA(), methodB(), ...) aren't used anywhere else in your code, you can implement the runnable interface in place with an anonymous class. Below is the previous example written in that form:

class A {
    public static void main(String... args) {
        new A().doSameThing(1, new Runnable() {
            public void run() {
                System.out.println("Hello World");
            }
        });
    }
    void doSameThing(int x, Runnable method) {
        method.run();
    }
}

Since Runnable is a functional interface, you could even go as far as using a lambda expression for this.

class A {
    public static void main(String... args) {
        new A().doSameThing(1, () -> {    
            System.out.println("Hello World");
        });
    }
    void doSameThing(int x, Runnable method) {
        method.run();
    }
}

答案2

得分: 0

如果您可以使用Java 1.8(及更高版本),您可以将方法传递为函数:

Function<Integer> method = (x) -> { //在这里执行操作 };

在doSameThing函数中

```java
void doSameThing(int x, Function<Integer> fn) {
   fn.apply(x);
}
英文:

If you can use java 1.8 (and above), you can pass the method as a function

Function&lt;Integer&gt; method = (x) -&gt; { //do something here }

And in doSameThing

doSameThing(int x, Function&lt;Integer&gt; fn) {
   fn.apply(x)
}

huangapple
  • 本文由 发表于 2020年4月9日 08:59:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/61112344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定