2

我有一个像

class A {

    private String property1;

    private String property2;

    private String property3;

    // constructor , getters , setters 

}

是否可以按照它们在源文件中出现的顺序获取此类属性名称的列表/数组?像["property1", "property2", "property3"]

4

3 回答 3

2

答案是你不能。您需要的信息在运行时无法从 .class 文件中获得。

在我的代码的其他一些部分,我需要按特定顺序“打印”这个类的数据。真实案例中的这个类有很多属性并且可以改变(作为顺序)所以,我可以自己编写这个数组/列表来获得我需要的顺序,但如果可以从类中得到它,那就是对我更好。

这里有一些更好的方法来解决这个问题:

  • 在打印之前按名称或类型名称或有意义的方式对属性进行排序。
  • 在定义 bean 属性顺序的 bean 类(或另一个类)中嵌入一个数组。
  • 创建一个单独的元数据文件来指定 bean 属性顺序。

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.

于 2012-05-21T22:45:56.113 回答
1

可以获得此类属性名称的列表/数组

是的,使用Class.getDeclaredFields()

按照它们在源文件中出现的顺序

不,除非您解析源文件,否则没有任何保证。

于 2012-05-21T22:10:42.507 回答
1

这并不完全可能。Class#getDeclaredFields不保证返回字段的顺序。但是,在我刚刚进行的测试中,这些字段确实是按照它们的声明顺序返回的。

于 2012-05-21T22:11:11.790 回答