Question

Javassist's CtClass has a few methods, such as getFields() and getMethods(). I was wondering if these methods offer any guarantee as to their ordering.

Specifically, I'd like to know if using getFields() on a class will produce and array of CtFields where the first field in the array is the first field declared in the file and so forth. So, is this order guaranteed? If not, is there anything that can offer this guarantee? The javadocs give no information on the matter. I've tried annotations that carry order (e.g. @X(1) private int first;), but it'd be easier if I could reflect this sort of thing without the need for annotations?

If it's still not clear, I'd like something like:

public class Class {
    public int x;
    public float y;
    public Object z;
}

to produce an array of CtFields specifically and consistently ordered x, y, z.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top