With JDK7, the reflection API has changed and now the methods returned by getDeclaredMethods() are not returned in the order in which they are declared in the source file.
Now my question is, does the .class file generated by javac contains methods in the same order in which they were defined in the source file OR it can write methods in random order too?
A Java class file is usually produced by a Java compiler from Java programming language source files ( . java files) containing Java classes (alternatively, other JVM languages can also be used to create class files). If a source file has more than one class, each class is compiled into a separate class file.
The javap command disassembles one or more class files. Its output depends on the options used. If no options are used, javap prints out the package, protected, and public fields and methods of the classes passed to it. javap prints its output to stdout.
Use the -d option to specify an output directory in which to put the compiled class files.
Detailed Solution. The javac command in Java compiles a program from a command prompt. It reads a Java source program from a text file and creates a compiled Java class file. The Railway Recruitment Board (RRB) is soon going to release the official notification for the RRB JE IT 2022.
Class.getDeclaredMethods API is clear about this "...The elements in the array returned are not sorted and are not in any particular order...". Most likely the reason of that is that javac is not obliged to generate methods in .class in any particular order.
The Binary Compatibility chapter of the Java Language Specification is explicit about the fact that reordering of elements in the class files is permitted:
[...] 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.
That means that the order in which they appear in the .class file is not dictated by the specifications. If you want to rely on it, you have to either (1) know for a fact that your specific implementation uses the same order as the definition order (testing it, like you've done, is a good idea but does not guarantee anything), or (2) change the order yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With