If you look at one of the implementations of CtClass
, like CtClassType
, you will see that getMethods()
is implemented that way:
public CtMethod[] getMethods() {
HashMap h = new HashMap();
getMethods0(h, this);
return (CtMethod[])h.values().toArray(new CtMethod[h.size()]);
}
According to the HashMap
javadoc:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
So, you have absolutely no guarantee in what order you will get the methods.
For the fields, the code is a lot more complicated, but it seems that the raw class file is read as an InputStream
:
DataInputStream in = new DataInputStream(
new FileInputStream(args[0]));
ClassFile w = new ClassFile(in);
And the fields are created as they are read from this stream:
fields = new ArrayList();
for (i = 0; i < n; ++i)
addField2(new FieldInfo(cp, in));
So, the fields are created in the order they are in the class file.
However, reading the JVM Specification and the Java Language Specification, I see no reference to the fields order in the generated class; this sentence from the Java Specification even seems to indicate that the fields order is not important:
Using their scheme, 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.
So I think that you have absolutely no guarantee on the fields order too.
I tried to run javassist.tools.Dump
on a test class I created with a large number of fields and methods, and it seems that fields and methods are printed in the source order, but I still think that nothing guarantee it.