Setting up different Java class fields value by a single value on some counter value?
In a Java class, having similar kind of fields like:
public class User {
private String user_Id_1;
private String user_Id_2;
private String user_Id_3;
private String user_Id_4;
...
public void setUserId(int num, String user_Id) {
switch (num) {
case 1: setUser_Id_1(user_Id); break;
case 2: setUser_Id_2(user_Id); break;
case 3: setUser_Id_3(user_Id); break;
case 4: setUser_Id_4(user_Id); break;
....
}
}
}
The requirement is - The User class field names resemble the exact field names in generated editable PDF Form like user_Id_1, user_Id_2 etc. For the 1st user record, the form field 'user_Id_1' must be set with value of "user_Id" ("user_Id" -> this value maps to the database field value), For the 2nd user record, the form field 'user_Id_2' must be set with same value of "user_Id", and so on.
How to reduce the multiple switch-case/if statements?
My suggestion: use reflection iterating the fields
for( Field field : User.class.getDeclaredFields() ){
// explore if necessary e.g.
if( field.getName().startsWith( "yourCriteria" )
&& field.getType().equals( String.class ) ){
boolean restoreAccessible = field.canAccess( this );
field.setAccessible( true );
field.set( this, field.getName() );
field.setAccessible( restoreAccessible );
}
}
You need the accessible-shenanigans to surcome private and protected access. It might even work if the code is part of the User-class - I did not check the indirection via the Field object there. If the code is not part of your User you need to replace field.canAccess( this ) by field.canAccess( yourInstance );