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

前端 未结 22 1783
太阳男子
太阳男子 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:14

    New Java 8 Functional Interfaces and Method References using the :: operator.

    Java 8 is able to maintain method references ( MyClass::new ) with "@ Functional Interface" pointers. There are no need for same method name, only same method signature required.

    Example:

    @FunctionalInterface
    interface CallbackHandler{
        public void onClick();
    }
    
    public class MyClass{
        public void doClick1(){System.out.println("doClick1");;}
        public void doClick2(){System.out.println("doClick2");}
        public CallbackHandler mClickListener = this::doClick;
    
        public static void main(String[] args) {
            MyClass myObjectInstance = new MyClass();
            CallbackHandler pointer = myObjectInstance::doClick1;
            Runnable pointer2 = myObjectInstance::doClick2;
            pointer.onClick();
            pointer2.run();
        }
    }
    

    So, what we have here?

    1. Functional Interface - this is interface, annotated or not with @FunctionalInterface, which contains only one method declaration.
    2. Method References - this is just special syntax, looks like this, objectInstance::methodName, nothing more nothing less.
    3. Usage example - just an assignment operator and then interface method call.

    YOU SHOULD USE FUNCTIONAL INTERFACES FOR LISTENERS ONLY AND ONLY FOR THAT!

    Because all other such function pointers are really bad for code readability and for ability to understand. However, direct method references sometimes come handy, with foreach for example.

    There are several predefined Functional Interfaces:

    Runnable              -> void run( );
    Supplier           -> T get( );
    Consumer           -> void accept(T);
    Predicate          -> boolean test(T);
    UnaryOperator      -> T apply(T);
    BinaryOperator -> R apply(T, U);
    Function         -> R apply(T);
    BiFunction     -> R apply(T, U);
    //... and some more of it ...
    Callable           -> V call() throws Exception;
    Readable              -> int read(CharBuffer) throws IOException;
    AutoCloseable         -> void close() throws Exception;
    Iterable           -> Iterator iterator();
    Comparable         -> int compareTo(T);
    Comparator         -> int compare(T,T);
    

    For earlier Java versions you should try Guava Libraries, which has similar functionality, and syntax, as Adrian Petrescu has mentioned above.

    For additional research look at Java 8 Cheatsheet

    and thanks to The Guy with The Hat for the Java Language Specification §15.13 link.

提交回复
热议问题