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

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

    oK, this thread is already old enough, so very probably my answer is not helpful for the question. But since this thread helped me to find my solution, I'll put it out here anyway.

    I needed to use a variable static method with known input and known output (both double). So then, knowing the method package and name, I could work as follows:

    java.lang.reflect.Method Function = Class.forName(String classPath).getMethod(String method, Class[] params);
    

    for a function that accepts one double as a parameter.

    So, in my concrete situation I initialized it with

    java.lang.reflect.Method Function = Class.forName("be.qan.NN.ActivationFunctions").getMethod("sigmoid", double.class);
    

    and invoked it later in a more complex situation with

    return (java.lang.Double)this.Function.invoke(null, args);
    
    java.lang.Object[] args = new java.lang.Object[] {activity};
    someOtherFunction() + 234 + (java.lang.Double)Function.invoke(null, args);
    

    where activity is an arbitrary double value. I am thinking of maybe doing this a bit more abstract and generalizing it, as SoftwareMonkey has done, but currently I am happy enough with the way it is. Three lines of code, no classes and interfaces necessary, that's not too bad.

提交回复
热议问题