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

前端 未结 22 1772
太阳男子
太阳男子 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: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); } }
    

提交回复
热议问题