我有一个像这样的类(class)
class A {
private String property1;
private String property2;
private String property3;
// constructor , getters , setters
}
是否可以按照此类属性在源文件中出现的顺序获取其属性名称的列表/数组?就像[“属性1”,“属性2”,“属性3”]
最佳答案
答案是你不能。您需要的信息在运行时无法从 .class 文件中获得。
In some other parts of my code i need to "print" the data of this class in certain order. This class in the real case has a lot of properties and can change (as the order) so, i can write this array/list by myself to get the order i need but if it is possible to get it from the class it would be better for me.
这里有一些更好的方法来解决这个问题:
- 在打印之前按名称或类型名称或有意义的名称对属性进行排序。
- 在定义 bean 属性顺序的 bean 类(或其他类)中嵌入一个数组。
- 创建一个单独的元数据文件来指定 Bean 属性顺序。
您可以对源代码进行一些构建时预处理,以提取属性的顺序并将它们写入文件。但坦白说,我觉得还是把这些方面分开比较好;例如以便您的系统集成商/最终用户可以在不更改源代码的情况下调整属性顺序。
关于java - 获取 java bean 属性名称的列表/数组,按照它们在源文件中出现的顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10693299/