Juan Antonio
Juan Antonio

Reputation: 2604

How compress switch structure in Java?

I have a conditional structure with Switch in Java where I have a lot of cases when the code to execute is very similar. The only one difference is the name of a variable. It's similar to:

 switch(n){
            case 1:
                tM=getString(R.string.tM1);
                tD=getString(R.string.tD1);
                break;
            case 2:
                tM=getString(R.string.tM2);
                tD=getString(R.string.tD2);
                break;

            ...

            case n:
                tM=getString(R.string.tMn);
                tD=getString(R.string.tDn);
                break;

            ...

            case 20:
                tM=getString(R.string.tM20);
                tD=getString(R.string.tD20);
                break;

            default:
                tM="";
                tD="";
                break;

        }

The code is too long and it's possible that I need add more cases with the similar structure.

So, How I can write this in two lines? I search something like this:

tM=getString(R.string.tM<n>);
tD=getString(R.string.tD<n>);

How can do this? There are some possible form? I tried several things but I don't found the solution. Thanks you very much.

Upvotes: 0

Views: 248

Answers (1)

AlmasB
AlmasB

Reputation: 3407

If n always refers to R.string.tMn and R.string.tDn, you can use Java reflection.

Field field = R.string.class.getField("tM" + n);
tM = getString((String)field.get(null));

Same for tD

Assuming getString() method takes a String as param and R.string.tMn is a String. If not, just typecast to whatever type is appropriate

Upvotes: 2

Related Questions