I am generating a report for a customer of our company.
I have a abstract class with lots of static final int members:
public abstract class Customer_ItemIDs {
public static final int item_001 = 34535;
public static final int item_002 = 23455;
public static final int item_003 = 74565;
public static final int item_004 = 83480;
...
public static final int item_122 = 65487;
}
In my class where I generate my report I use them like this (simplified a bit):
int itemID_004;
itemID_004 = Customer_ItemIDs.item_004;
Now there is a change in the requirement.
I need to support another Customer with totally different ItemIDs which i want to put in another static class. The name of the items stay the same, just the values are different.
public abstract class CustomerB_ItemIDs {
public static final int item_001 = 17538;
public static final int item_002 = 56756;
public static final int item_003 = 94445;
public static final int item_004 = 93757;
...
public static final int item_122 = 69483;
}
How do I properly parametrize this, without changing every line of code where I initialize my itemIDs? I don't want to initialize the itemIDs like this:
int itemID_004;
if (customer == customerA) {
itemID_004 = CustomerA_itemIDs.item_004;
}
else if (customer == customerB) {
itemID_004 = CustomerB_itemIDs.item_004;
}
I would like to change as little as possible.
I think you should try Java Reflections:
java.lang.reflect
To not to interrupt the existing classes source code, I would create a method which will return
HashMap
with all field's name as akey
and its int values asvalue
, using provided class name as a parameter:Here is simple example, which will print you all fields with values for provided Class: