我有一个像
class A {
private String property1;
private String property2;
private String property3;
// constructor , getters , setters
}
是否可以按照它们在源文件中出现的顺序获取此类属性名称的列表/数组?像["property1", "property2", "property3"]
我有一个像
class A {
private String property1;
private String property2;
private String property3;
// constructor , getters , setters
}
是否可以按照它们在源文件中出现的顺序获取此类属性名称的列表/数组?像["property1", "property2", "property3"]
答案是你不能。您需要的信息在运行时无法从 .class 文件中获得。
在我的代码的其他一些部分,我需要按特定顺序“打印”这个类的数据。真实案例中的这个类有很多属性并且可以改变(作为顺序)所以,我可以自己编写这个数组/列表来获得我需要的顺序,但如果可以从类中得到它,那就是对我更好。
这里有一些更好的方法来解决这个问题:
You could do some build time pre-processing of your source code to extract the order of the properties and (say) write them to a file. But frankly, I think it is better to detach these aspects; e.g. so that your system integrators / end-users could tweak the property order without changing the source code.
这并不完全可能。Class#getDeclaredFields
不保证返回字段的顺序。但是,在我刚刚进行的测试中,这些字段确实是按照它们的声明顺序返回的。