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

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

    Prior to Java 8, nearest substitute for function-pointer-like functionality was an anonymous class. For example:

    Collections.sort(list, new Comparator<CustomClass>(){
        public int compare(CustomClass a, CustomClass b)
        {
            // Logic to compare objects of class CustomClass which returns int as per contract.
        }
    });
    

    But now in Java 8 we have a very neat alternative known as lambda expression, which can be used as:

    list.sort((a, b) ->  { a.isBiggerThan(b) } );
    

    where isBiggerThan is a method in CustomClass. We can also use method references here:

    list.sort(MyClass::isBiggerThan);
    
    0 讨论(0)
  • 2020-11-22 16:29

    Sounds like a strategy pattern to me. Check out fluffycat.com Java patterns.

    0 讨论(0)
  • 2020-11-22 16:31

    You may also be interested to hear about work going on for Java 7 involving closures:

    What’s the current state of closures in Java?

    http://gafter.blogspot.com/2006/08/closures-for-java.html
    http://tech.puredanger.com/java7/#closures

    0 讨论(0)
  • 2020-11-22 16:35

    To do the same thing without interfaces for an array of functions:

    class NameFuncPair
    {
        public String name;                // name each func
        void   f(String x) {}              // stub gets overridden
        public NameFuncPair(String myName) { this.name = myName; }
    }
    
    public class ArrayOfFunctions
    {
        public static void main(String[] args)
        {
            final A a = new A();
            final B b = new B();
    
            NameFuncPair[] fArray = new NameFuncPair[]
            {
                new NameFuncPair("A") { @Override void f(String x) { a.g(x); } },
                new NameFuncPair("B") { @Override void f(String x) { b.h(x); } },
            };
    
            // Go through the whole func list and run the func named "B"
            for (NameFuncPair fInstance : fArray)
            {
                if (fInstance.name.equals("B"))
                {
                    fInstance.f(fInstance.name + "(some args)");
                }
            }
        }
    }
    
    class A { void g(String args) { System.out.println(args); } }
    class B { void h(String args) { System.out.println(args); } }
    
    0 讨论(0)
提交回复
热议问题