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

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

    You can also do this (which in some RARE occasions makes sense). The issue (and it is a big issue) is that you lose all the typesafety of using a class/interface and you have to deal with the case where the method does not exist.

    It does have the "benefit" that you can ignore access restrictions and call private methods (not shown in the example, but you can call methods that the compiler would normally not let you call).

    Again, it is a rare case that this makes sense, but on those occasions it is a nice tool to have.

    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    class Main
    {
        public static void main(final String[] argv)
            throws NoSuchMethodException,
                   IllegalAccessException,
                   IllegalArgumentException,
                   InvocationTargetException
        {
            final String methodName;
            final Method method;
            final Main   main;
    
            main = new Main();
    
            if(argv.length == 0)
            {
                methodName = "foo";
            }
            else
            {
                methodName = "bar";
            }
    
            method = Main.class.getDeclaredMethod(methodName, int.class);
    
            main.car(method, 42);
        }
    
        private void foo(final int x)
        {
            System.out.println("foo: " + x);
        }
    
        private void bar(final int x)
        {
            System.out.println("bar: " + x);
        }
    
        private void car(final Method method,
                         final int    val)
            throws IllegalAccessException,
                   IllegalArgumentException,
                   InvocationTargetException
        {
            method.invoke(this, val);
        }
    }
    

提交回复
热议问题