简体   繁体   English

java Hashmap将键ID映射到方法名称

[英]java Hashmap mapping key id to method names

I have a java code scenario where I have to populate the key and value entry in a HashMap. 我有一个Java代码方案,必须在HashMap中填充键和值条目。 The key Id's I need to use are predefined and the corresponding value I generate via code logic processing something like this 我需要使用的密钥ID是预定义的,并且我通过代码逻辑处理类似这样生成的相应值

Key=16 value= *result of method calculateZipWeather()*
Key=23 value= *result of method calculateZipCensus()*
key=37 value = *result of method calulateZipCrime()*

The way i do this today is something like this 我今天这样做的方式是这样的

String zipweather = calculateZipWeather()  
mapObj.put(16,zipweather)

I wanted to check if there is a way to maintain static external mapping between key Id and the corresponding method name which populates it rather than hard coding key id in the java code. 我想检查是否有一种方法可以维护键ID和填充它的相应方法名之间的静态外部映射,而不是在Java代码中硬编码键ID。

Let me know your thoughts. 让我知道你的想法。

This is how you can do it using Reflection: 您可以使用反射来做到这一点:

Suppose you have following class which contains all the 'calculate' methods: 假设您有以下包含所有“计算”方法的类:

public class Operations {

    public String calculateZipWeather() {
        return "Zip Weather";
    }

    public String calculateZipCensus() {
        return "Zip Census";
    }

    public String calculateZipCrime() {
        return "Zip Crime";
    }

}

Then following is how you do what you need (Method is java.lang.reflect.Method ): 接下来是您如何做所需的事情(方法是java.lang.reflect.Method ):

public class Populate {

    //This map contains mapping of your 'keys' with 'methods' which need to be invoked for those keys 
    private static Map<Integer, Method> keyOperationMapping;

    //static initializer block to initialize the above map
    static {
        keyOperationMapping = new HashMap<Integer, Method>();

        try {
            //Getting the 'Method' object with method name as 'calculateZipWeather' from 'Operations' class and mapping it with key 
            Method method16 = Operations.class.getDeclaredMethod("calculateZipWeather");
            keyOperationMapping.put(16, method16);
        } 
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }

        try {
            //Getting the 'Method' object with method name as 'calculateZipCensus' from 'Operations' class. 
            Method method23 = Operations.class.getDeclaredMethod("calculateZipCensus");
            keyOperationMapping.put(16, method23);
        } 
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }

        //Similary add more key-value pairs

    }

    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        //You need an Operations object on which the methods will be called/invoked 
        Operations operations = new Operations();

        //Map to store your results
        Map<Integer, String> calculatedZips = new HashMap<Integer, String>();
        //Iterate over all key-value pairs of key with methods
        for(Map.Entry<Integer, Method> entry : keyOperationMapping.entrySet()) {
            //Get method to be invoked
            Method methodToInvoke = entry.getValue();

            //Invoke the method on operations object, you can also pass arguments here if your method requires
            String zipValue = (String) methodToInvoke.invoke(operations);

            //Get key which will be your argum
            int zipKey = entry.getKey();

            calculatedZips.put(zipKey, zipValue);
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM