Home > database >  Substitutions in variable name in java
Substitutions in variable name in java

Time:12-07

Not sure if this is possible in JAVA, and also don't know what it's called so I'm not sure what to look for, but if it is possible I really wanted to implement the same in my logic. I know we can substitute value but how to substitute variable that I am not sure.

public interface Constants {
 GENDER_${MALE} = "where Gender = 'MALE' ";
 GENDER_${FEMALE} = "where Gender = 'FEMALE' ";
}

public class Impl {
  System.out.println(Constants.GENDER_MALE);
}

Expected O/P : where Gender = 'MALE';

I just don't want to use if else condition, if Male then return male specific where clause else female.. because in actual code there are almost 30-35 if else conditions, just want to reduce that, if possible.

CodePudding user response:

As @GhostCat said, This is not possible in java as java is statically typed. What you can do is that you can make a class of constants like this,

public class Constants {
 String GENDER_MALE = "where Gender = 'MALE' ";
 String GENDER_FEMALE = "where Gender = 'FEMALE' ";
}

and use like this,

System.out.println(Constants.GENDER_MALE);

CodePudding user response:

public enum Gender {
    FEMALE, MALE;
    public String where() {
        return "where Gender = '"   this   "' ";
    }
}

String s = Gender.MALE.where();

As this is probably an attempt to large scale modelling:

public static <T extends Enum<T>> String where(T value) {
     return "where Gender = '"   value   "' ";
}

Do not expect too much result from this all.

CodePudding user response:

You can put where expressions in Map where key is you variable possible value, for example:

HashMap<String, String> whereMap = new HashMap<>();

map.put("MALE",   "where Gender = 'MALE' ");
map.put("FEMALE", "where Gender = 'FEMALE' ");

And instead of using condition do substitution by retrieved by key value:

String var = "MALE";
System.out.println(MessageFormat.format("SELECT * FROM EMP {0}", whereMap.get(var)));
  • Related