[英]Substitutions in variable name in java
不确定这在 JAVA 中是否可行,也不知道它叫什么,所以我不确定要查找什么,但如果可能的话,我真的想在我的逻辑中实现相同的功能。 我知道我们可以替换值,但是我不确定如何替换变量。
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';
我只是不想使用 if else 条件,如果 Male 然后返回男性特定的 where 子句 else female .. 因为在实际代码中几乎有 30-35 个 if else 条件,如果可能的话,只想减少它。
您可以将 where 表达式放在 Map 中,其中 key 是您可变的可能值,例如:
HashMap<String, String> whereMap = new HashMap<>();
map.put("MALE", "where Gender = 'MALE' ");
map.put("FEMALE", "where Gender = 'FEMALE' ");
而不是使用条件通过键值检索进行替换:
String var = "MALE";
System.out.println(MessageFormat.format("SELECT * FROM EMP {0}", whereMap.get(var)));
正如@GhostCat所说,这在 java 中是不可能的,因为java 是静态类型的。 你可以做的是你可以制作一个像这样的常量的 class,
public class Constants {
String GENDER_MALE = "where Gender = 'MALE' ";
String GENDER_FEMALE = "where Gender = 'FEMALE' ";
}
并像这样使用,
System.out.println(Constants.GENDER_MALE);
public enum Gender {
FEMALE, MALE;
public String where() {
return "where Gender = '" + this + "' ";
}
}
String s = Gender.MALE.where();
因为这可能是对大规模建模的尝试:
public static <T extends Enum<T>> String where(T value) {
return "where Gender = '" + value + "' ";
}
不要期望这一切有太多的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.