Java 读取字符串作为变量的引用

Java 读取字符串作为变量的引用,java,string,reference,Java,String,Reference,我想从我的类数据源中读取一个参数: public class Datasource { public final static String M = "M"; public final static String M_SHEET ="Config"; public final static String M_LOC = "C6"; public final static int M_DEFAULT = 2; // default value ... } 通过使用方法changeParamet

我想从我的类数据源中读取一个参数:

public class Datasource {
public final static String M = "M"; 
public final static String M_SHEET ="Config";
public final static String M_LOC = "C6";
public final static int M_DEFAULT = 2; // default value
...
}
通过使用方法changeParameters:

public static void changeParameter(String param, double value) {
    String parameter = param.toUpperCase(); // uppercase to match the final variable from Datasource

    InputStream inp = new FileInputStream(Datasource.EXCELFILENAME);
    // Excelconnection
    Workbook wb = WorkbookFactory.create(inp);
    String sheetName = "Datasource." + parameter + "_SHEET";
    Sheet sheet = wb.getSheet(sheetName);
    String excelCell = "Datasource." + parameter + "_LOC";
    int rowInt = getRow(excelCell);
    Row row = sheet.getRow(rowInt);
    int cellInt = getCell(excelCell);
    Cell cell = row.createCell(cellInt);
    cell.setCellValue(value);
    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream(Datasource. EXCELFILENAME);
    wb.write(fileOut);
    fileOut.close();
}

getRow和getCell都使用字符串作为参数来获取Excelrow和Excelcolumn。有人知道我如何才能做到字符串sheetName和excelCell不被视为字符串,而是被视为来自数据源的字符串的引用(例如,访问“C6”而不是“Datasource.M_LOC”?

您可以使用反射来实现这一点

Class clazz = DataSource.class;
Field field = clazz.getField("M_LOC"); // use getDeclaredField if the field isn't public
String str = (String)field.get(null); // it's a static field, so no need to pass in a DataSource reference
或者,在DataSource中放置一个hashmap,字段名作为键,字段值作为值


我相信
getField
getDeclaredField
都是线性时间方法,因此如果可能,您应该缓存它们的结果。

您可以使用反射来实现这一点

Class clazz = DataSource.class;
Field field = clazz.getField("M_LOC"); // use getDeclaredField if the field isn't public
String str = (String)field.get(null); // it's a static field, so no need to pass in a DataSource reference
或者,在DataSource中放置一个hashmap,字段名作为键,字段值作为值


我相信
getField
getDeclaredField
都是线性时间方法,所以如果可能的话,你应该缓存它们的结果。

如果你要通过字符串引用东西,为什么要将它们存储为单个变量?为什么不使用
映射
?这样,当你需要访问引用的字符串时de>“Datasource.M_LOC”,您可以使用

Map<String,String> referenceMap;
...
referenceMap.get(parameter+"_LOC");
地图参考地图;
...
referenceMap.get(参数+“_LOC”);

如果要通过字符串引用对象,为什么要将它们存储为单个变量?为什么不使用
映射
?这样,当需要访问
“Datasource.M_LOC”
引用的字符串时,可以使用

Map<String,String> referenceMap;
...
referenceMap.get(parameter+"_LOC");
地图参考地图;
...
referenceMap.get(参数+“_LOC”);

谢谢,这对我帮助很大!谢谢,这对我帮助很大!