在 JDK7 中,反射 API 发生了变化,现在 getDeclaredMethods() 返回的方法不按照它们在源文件中声明的顺序返回。
现在我的问题是,由 javac 生成的 .class 文件是否包含方法以相同的顺序在源文件中定义它们,或者它也可以以随机顺序编写方法? p>
最佳答案
Binary Compatibility chapter of the Java Language Specification明确指出允许对类文件中的元素进行重新排序:
[...] here is a list of some important binary compatible changes that the Java programming language supports:
[...]
Reordering the fields, methods, or constructors in an existing type declaration.
[...]
Reordering the list of direct superinterfaces of a class or interface.
这意味着它们在 .class 文件中出现的顺序不是由规范规定的。如果你想依赖它,你必须 (1) 知道一个事实,即你的特定实现使用与定义顺序相同的顺序(测试它,就像你所做的那样,是个好主意,但不能保证任何事情),或 (2) 自行更改顺序。
关于java - javac生成的类文件中的方法顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14019240/