What's the nearest substitute for a function pointer in Java?

前端 未结 22 1770
太阳男子
太阳男子 2020-11-22 15:32

I have a method that\'s about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that\'s going to change one li

22条回答
  •  执念已碎
    2020-11-22 16:12

    Anonymous inner class

    Say you want to have a function passed in with a String param that returns an int.
    First you have to define an interface with the function as its only member, if you can't reuse an existing one.

    interface StringFunction {
        int func(String param);
    }
    

    A method that takes the pointer would just accept StringFunction instance like so:

    public void takingMethod(StringFunction sf) {
       int i = sf.func("my string");
       // do whatever ...
    }
    

    And would be called like so:

    ref.takingMethod(new StringFunction() {
        public int func(String param) {
            // body
        }
    });
    

    EDIT: In Java 8, you could call it with a lambda expression:

    ref.takingMethod(param -> bodyExpression);
    

提交回复
热议问题