简体   繁体   中英

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

I have two java class with constants, For Ex:

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";
    ...
}

Now, I want to load these constants into a, Map< String,String> classPropertyMap = new HashMap<>(); in Such a way that, Key for this map must be a constant from FirstClass and corresponding value must be a constant from SecondClass.

If it was just one class I could use reflection to load the fields, now since the constants are from two class, how could this be done?

Finally after loading the map, the contents of the map must be something like this:

First element : key and value is < STRING_A, STRING_AA>

Second element : key and value is < STRING_B, STRING_BA>

Third element : key and value is < STRING_C, STRING_CA>

I think if you really need it, the most robust way is to put the properties to a map explicitly.

I mean map.put(FirstClass.STRING_A, SecondClass.STRING_AA); and so on.

If you use reflection you rely on the properties and their declaration order never changes. If some new property is introduced in the library, it can break your code.

Try something like below, seems you can achieve.

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

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

Try This:

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++;
}

Hope that works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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