Field initialization code executed more than once

13 views
Skip to first unread message

Udo

unread,
May 30, 2013, 5:50:47 AM5/30/13
to java2...@googlegroups.com
In some case the member field initialization code (defined through the function passed to Clazz.prepareFields) is executed more than once.

Here a simple example to demonstate the problem:

---  
public class BaseClass {
    public static int count = 0;

    public int index = count++;
}
---

The BaseClass holds a global (static) counter for its objects, and every instance of BaseClass (or its subclasses) holds its 'index'. So the first BaseClass object will have index == 0, the second index == 1 and so on.


Now we extend this class in two steps:

---
public class SubClass extends BaseClass {
    public SubClass() {
        super();
        int x = 0;
    }
}
---
public class SubSubClass extends SubClass {

    public static void main(String[] args) {
        SubSubClass obj = new SubSubClass();
        System.out.println(obj.index);

        SubSubClass obj2 = new SubSubClass();
        System.out.println(obj2.index);
    }
}
---

SubSubClass.main just creates two instances of SubSubClass and prints out their indices.

Running this in native Java prints out (as expected):
0
1


However running this using Java2Script prints out:
1
3


This shows the initialization code for the index field is executed twice for each instance. 

With deeper inheritance you can get even more executions of the field initialization code.


Up to now I found no way to work around this problem. Any suggestions?



Udo

Udo

unread,
May 30, 2013, 6:05:31 AM5/30/13
to java2...@googlegroups.com
Moving all member field initialization code into the constructor is a possible workaround. 

For my example the BaseClass would then look like this:

public class BaseClass {

    public static int count = 0;


    public int index;

    

    public BaseClass() {

        index = count++;

    }

}


This 'solves' the issue. However I am translating a large project to JavaScript so touching nearly every file is not really something I would want to do. 

So maybe there is a fix to the Java2Script compiler?

Udo

Reply all
Reply to author
Forward
0 new messages