I gather that some here would to see structs added to Java to improve the efficiency of communications with other systems (notably hardware). Rather than add a new language feature I propose a class (below) which the JIT could optimise to achieve the same efficiency as a C struct.
public abstract class Struct {
private ByteBuffer buffer;
private int position;
protected Struct(ByteBuffer b, ByteOrder order) {
buffer = b.slice();
buffer.order(order);
}
public abstract int size();
public int alignment() {return 1;}
public final int position() {return position;}
public final void position(int p) {
if (p < 0 || p+size() > buffer.limit()) throw new IndexOutOfBoundsException();
if ((p&(alignment()-1)) != 0) throw new IllegalArgumentException("Bad alignment");
position = p;
}
public final void setIndex(int i) {
position(i*size());
}
protected int getInt(int offset) {return buffer.getInt(position+offset);}
protected void setInt(int offset, int value) {buffer.putInt(position+offset, value);}
}
class MyStruct extends Struct {
public MyStruct(ByteBuffer buf) {super(buf, ByteOrder.nativeOrder());}
public int size() {return 8;}
public int getX() {return getInt(0);}
public void setX(int x) {setInt(0, x);}
public int getY() {return getInt(4);}
public void setY(int y) {setInt(4, y);}
}
Now the JIT should be able to optimise this provided that
[]the size() method returns a constant
[]The supplied ByteOrder is suitable. Note that the byte order can’t be changed after construction of the Struct.
[]The calls to the get and set methods have constant values for the offset. Or where the value can be deduced to always lie in the range 0 … size()-sizeof(type).
[]The alignment is constant and suitable for the processor
This mechanism also allows structs to contain 'union’s and you can put padding where appropriate.
Thus the performance objective can be achieved by adding just one ‘special’ class and modifying JITs to make use of the properties of that class. Even better the code will work with existing JVMs without change (just slower).
OK, so you have to do a bit more typing (or use a wizard), but it ought to be far easier to get this change through the JCP than one which requires a change to the language itself.