gpt4 book ai didi

Java常量通过构建字符串进行实例化

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:27 25 4
gpt4 key购买 nike

我正在尝试从常量文件中读取键值对。当我直接使用类名和字段名时它可以工作,但是当我动态构造类+字段组合时它不起作用。如何协商这个问题?

以下是我的常量文件

Public interface Constants
{
String DEV_SELECT_STATEMENT = “DEV_INT_SQL_SELECT_STATEMENT”
String INT_SELECT_STATEMENT = “DEV_INT_SQL_SELECT_STATEMENT”
}

查询.properties文件

DEV_INT_SQL_SELECT_STATEMENT =  “SELECT * FROM SOME TABLE”;

JAVA 类文件//这有效

public someClass
{
public someMethod() //This works
{
String sqlStatement = QueryLoader.getStatement(Constants.DEV_SELECT_STATEMENT);
System.out.println("The key is :" + Constants. DEV_SELECT_STATEMENT);
System.out.println(“SqlStatement is : “ + sqlStatement);
}
}

关键是:DEV_INT_SQL_SELECT_STATEMENT

SqlStatement 是:SELECT * FROM SOME TABLE

 public someClass  //This does not work
{
public someMethod(String env) //This does not work
{
String queryKey = “Constants” +env + “_SELECT_STATEMENT “;
System.out.println(“The Key is : “ + queryKey);
String sqlStatement = QueryLoader.getStatement(queryKey);
System.out.println(“SqlStatement is : “ + sqlStatement);
}

关键是:Constants.DEV_SELECT_STATMENT//这不会给出值,而是给出一个字符串

SqlStatement 为:null

最佳答案

使用反射:

String fieldName = env+"_SELECT_STATEMENT";

String value = String.valueOf(Constants.class.getField(fieldName).get(null));

编辑:我注意到我做了一些非法的事情(Constants.class.getClass() 无效)

我如何测试编辑后的代码并且它可以工作。

关于Java常量通过构建字符串进行实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10520028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com