Java反射:按声明顺序获取字段和方法 [英] Java Reflection: Getting fields and methods in declaration order

查看:1861
本文介绍了Java反射:按声明顺序获取字段和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法按照声明的顺序使用反射获取类声明的字段(和方法)?根据文档, getFields() getDeclaredFields()等返回的方法和字段的顺序是undefined。

Is there any way to get a classes declared fields (and methods) in the order of declaration using reflection? According to the documentation, the ordering of Methods and Fields returned by getFields(), getDeclaredFields(), etc. is undefined.

根据 Java反射:类字段和方法的顺序是否标准化?

有没有更好的选择,即不必手动指定索引?

Are there any better options, i.e. not having to specify the index manually?

现在在你问我需要什么之前:我们有一个方法需要一个相当的大数据结构作为输入并对其进行冗长的计算。为了创建单元测试,我们创建了一个方法,该方法接受输入对象和输出实例,并创建Java源代码(设置输入,调用计算方法,然后断言正确的结果)作为输出。当字段按声明顺序写入时,此代码更具可读性。

Now before you ask what I need this for: we have a method that takes a quite big data structure as input and performs a lengthy calculation on it. To create unit tests, we made a method that takes an input object and an output instance and creates the Java source code (setting up input, invoking the calculation method, and asserting the correct results afterwards) as output. This code is much more readable when fields are written in declaration order.

推荐答案

使用jdk 6,反射字段为契约他们的申报单。在早期的jdk中并非如此。很明显,人们已经唠叨了。

With jdk 6, the reflected fields are in deed in their declaration order. In early jdk that wasn't the case. Apparently enough people have nagged.

虽然javadoc没有保证,但我仍然认为这个订单是合格的,我认为订单也将保留在未来的jdks中。

Although not guaranteed by javadoc, I would still take this order as granted, and I assume the order will be kept in future jdks too.

在您的应用程序中,与大多数应用程序一样,对声明顺序的依赖主要是虚荣 - 如果订单搞砸了,您的应用程序不会失败,它只会变得有点丑陋。

In your app, like in most apps, the dependency on the declaration order is mostly vanity - your app won't fail if the order screws up, it just become a little uglier.

这篇关于Java反射:按声明顺序获取字段和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆