How do I map a string to a function in Java?

At present, I have a bunch of Java classes that implement the processor interface, which means that they all have a processrequest (string key) method The idea is that each class has some (for example, < 10) member strings, and each class is mapped to a method in the class through the processrequest method, as shown below:

class FooProcessor implements Processor
{
    String key1 = "abc";
    String key2 = "def";
    String key3 = "ghi";
    // and so on...

    String processRequest(String key)
    {
        String toReturn = null;
        if (key1.equals(key)) toReturn = method1();
        else if (key2.equals(key)) toReturn = method2();
        else if (key3.equals(key)) toReturn = method3();
        // and so on...

        return toReturn;
    }

    String method1() { // do stuff }
    String method2() { // do other stuff }
    String method3() { // do other other stuff }
    // and so on...
}

You get the idea

This works fine for me, but now I need a runtime accessible mapping from key to function; Not every function actually returns a string (some return void). I need to dynamically access the return type of each function with a key in each class (using reflection) I already have an administrator who knows all the keys, but there is no mapping from key to function

My first instinct is to replace this map with an if else statement and use map < string, function > like JavaScript However, Java does not support first-class functions, so I have no luck I can dig a third-party library that allows me to handle first-class functions, but I haven't seen it yet. I doubt I need a new library

I also thought of putting these string keys into an array and using reflection to call methods by name, but I see two disadvantages of this method:

>My keys must be the same as the method name – or named in a specific consistent way to map them to the method name. > This seems to be slower than the current if else statement Efficiency is a concern because these methods are often called frequently. I want to reduce unnecessary overhead

TL; Dr: I'm looking for a clean, minimal overhead way to map a string to a function object that can call (and similar to) getreturntype () If it really suits my needs, I don't particularly want to use third-party libraries I also don't mind using reflection, although I strongly want to avoid using reflection for method lookup every time - maybe some caching strategies to combine maps and reflection

Think of a good way to get what I want? Cheers!

Solution

Can't you do string to method? You can then cache the methods needed to execute

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>