这个问题有多个部分,在最后一部分都会有意义:
是否可以在运行时以编程方式列出 Java 类中任何程序员定义的变量......?
我最近在 VB.Net 中编写了一个实用程序,它按名称列出了我项目中的所有表单,因此我可以从列表框中选择一个来运行(仅用于开发目的)。在 StackOverflow 上其他地方的帮助下,我能够将以下代码固定在一起,为了说明目的,这个例子被固定在一起......
System.Reflection.Assembly.GetExecutingAssembly().DefinedTypes(n).BaseType.FullName
在 Java 中可以做类似的事情来列出变量名吗?例如,MyInteger、MyString 或 MyObject。它就像 Visual Studio 中“Locals”窗口背后的功能(但我使用的是 Eclipse for Java)。
在过去 20 年的某个时候,在另一种编程语言中,我遇到了一个名为 Indirect(String varname) 的函数。它用于通过名称 访问原始变量。而“varname”参数本身可以是一个变量;它不一定是文字。这是一个显示其用法的示例:
int N1, N2, N3; // N1, N2, & N3 are all zero for (int i = 1; i < 4; i++){ Indirect("N" + i.toString) = 100 } // N1, N2, & N3 are now all 100
Java 是否具有与 Indirect() 等效的功能,或者是否有复制相同功能的方法......?
为了将所有这些结合在一起,以及整个论坛帖子的原因,是我编写了以下用于调试目的的程序,我将其放入我的类中以 CSV 格式输出变量值在开发过程中...
public String listVars(){ Object input[] = {var1, var2, var3, var4, var5}; // list of vars String output = ""; // output catcher int varCount = input.length; // get the length of the array for (int i = 0; i < varCount; i++){ // loop through the array output += "\"" + input[i] + "\""; // surround with quotes, append to output if (i < varCount-1){ // if the item NOT the last... output += ","; // append a comma to it } } return output; // return completed output }
我想做的是使用自动枚举变量的代码自动输入对象数组,这样我就不必将它们复制并粘贴到函数中。我假设在这样做时,一旦确定了它们的名称,就需要间接引用它们,以便可以在代码中访问它们的值。
PS - 按范围过滤变量会很好,例如“private”、“super”、“
最佳答案
- 在运行时列出类字段/方法
是的,你可以通过反射(reflection)来做到这一点。请参阅教程 here:
for (Field f : getClass().getDeclaredFields()) {
System.out.println("found " + f);
}
- “间接”访问
是的,使用上面的机制找到你想要祭坛的字段然后你可以设置它的值
Field f = ... //get it from somewhere
f.set(this, "new value");
您想要实现的目标听起来非常接近 j ava bean 概念。它的要点是您要为您的 getter 和 setter 方法遵守 getX()/setX() 命名约定,每个这样的对代表一个名为“x”的属性,然后您可以利用面向 bean 的库,例如 apache commons beanutils 来为您完成所有繁重的工作(我在上面告诉过您),就像这样:
Employee employee = ...;
String firstName = (String)PropertyUtils.getSimpleProperty(employee, "firstName");
String lastName = (String)PropertyUtils.getSimpleProperty(employee, "lastName");
... manipulate the values ...
PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
PropertyUtils.setSimpleProperty(employee, "lastName", lastName);
关于Java 在运行时按名称间接访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281155/