Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Order in generated class file by javac

Tags:

java

javac

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?

like image 213
Manish Avatar asked Dec 24 '12 09:12

Manish


People also ask

How is Java class file generated?

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.

What is Java javac Javap command for?

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.

Which command line do you use to tell javac compiler where compiled class files go?

Use the -d option to specify an output directory in which to put the compiled class files.

When you use the javac command which type of file gets created by the compiler?

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.


2 Answers

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.

like image 34
Evgeniy Dorofeev Avatar answered Sep 28 '22 05:09

Evgeniy Dorofeev


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.

like image 198
Oak Avatar answered Sep 28 '22 06:09

Oak