簡體   English   中英

使用常量迭代兩個類並將其字段加載到HashMap中

[英]Iterate over Two Class with constants and load their fields into a HashMap

我有兩個帶有常量的Java類,例如:

public class FirstClass {

 public static final String STRING_A = "STRING_A";
 public static final String STRING_B = "STRING_B";
 public static final String STRING_C = "STRING_C";
    ...
}


public class SecondClass {

 public static final String STRING_AA = "STRING_AA";
 public static final String STRING_BA = "STRING_BA";
 public static final String STRING_CA = "STRING_CA";
    ...
}

現在,我想將這些常量加載到Map <String,String> classPropertyMap = new HashMap <>();中。 以這種方式,此映射的Key必須是FirstClass的常量,而對應的值必須是SecondClass的常量。

如果這只是一個類,那么由於常量來自兩個類,我現在可以使用反射來加載字段,這怎么辦?

最后,加載地圖后,地圖的內容必須類似於以下內容:

第一個元素:鍵和值是<STRING_A,STRING_AA>

第二個元素:鍵和值是<STRING_B,STRING_BA>

第三個元素:鍵和值是<STRING_C,STRING_CA>

我認為,如果您確實需要它,最可靠的方法是將屬性明確地放入地圖。

我的意思是map.put(FirstClass.STRING_A, SecondClass.STRING_AA); 等等。

如果使用反射,則依賴屬性,並且它們的聲明順序永遠不會改變。 如果在庫中引入了一些新屬性,則可能會破壞您的代碼。

嘗試以下類似的方法,看來可以實現。

FirstClass first = new FirstClass();
Field[] fields = first.getClass().getFields();

SecondClass second = new SecondClass();
Field[] fields1 = second.getClass().getFields();

嘗試這個:

FirstClass first  = new FirstClass();    
String[] firstStrings = first.getStrings();
//Makes a String array, and fills it with the strings from the first class.

SecondClass second  = new SecondClass();    
String[] secondStrings = second.getStrings();    
//Makes a String array, and fills it with the strings from the second class.

HashMap<String, String> classPropertyMap = new HashMap<String, String>();
int i = 0;

//Now put strings with the same index number from both arrays into the 
//HashMap

while(i <= firstStrings.length()){
    classPropertyMap.put(firstStrings.get(i), secondStrings.get(i);
    i++;
}

希望能成功!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM