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

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

问题描述

有什么方法可以使用反射按照声明的顺序获取类声明的字段(和方法)?根据文档,getFields()getDeclaredFields() 等返回的方法和字段的顺序未定义.

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天全站免登陆