2016-04-04 82 views
2

我有一個java代碼場景,我必須填充HashMap中的鍵和值條目。 密鑰ID的我需要使用預定義和相應的價值我通過代碼邏輯生成處理這樣的事情java哈希映射密鑰id到方法名稱

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

我今天這個做的方法是這樣的

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

我想檢查是否有一種方法來維護鍵ID和填充它的相應方法名稱之間的靜態外部映射,而不是Java代碼中的硬編碼鍵ID。

讓我知道你的想法。

+2

使用反射將鍵值映射到方法名稱(或「方法」對象)。 – Thomas

回答

0

這是如何使用反射做到這一點:

假設你有以下類,它包含了所有的「計算」方法:

public class Operations { 

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

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

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

} 

然後下面是你怎麼做你所需要的(方法是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); 
     } 

    } 

}