P
Paul Chapman
I figured out the following interesting solution to the problem of returning
a value from a super ctor to a this ctor.
class Obj extends Header
{
final Handle handle;
final Mapper mapper;
private Obj(Cache cache, Handle handle, byte[] rawBytes,
int[] dataOffsetHolder)
{
super(cache, rawBytes, dataOffsetHolder);
this.handle = handle;
mapper = buildMapper(rawBytes, dataOffsetHolder[0]);
}
Obj(Cache cache, Handle handle, byte[] rawBytes)
{
this(cache, handle, rawBytes, new int[1]);
}
...
}
The problem was to retrieve an integer value from the super ctor. There's
no room to define a local temporary int[] variable before calling super,
because super() must be the first statement. But you can get a named
temporary int[] variable at the very beginning of a ctor by passing it in as
an argument.
The compiler is apparently clever enough to figure out that, despite the
fact that the second ctor doesn't set the final variables, they will
nevertheless be set by the ctor called with this().
However, if you rearrange things slightly:
private Obj(Cache cache, byte[] rawBytes, int[] dataOffsetHolder)
{
super(cache, rawBytes, dataOffsetHolder);
mapper = buildMapper(rawBytes, dataOffsetHolder[0]);
}
Obj(Cache cache, Handle handle, byte[] rawBytes)
{
this(cache, rawBytes, new int[1]);
this.handle = handle;
}
The compiler now reports two errors relating to whether handle has been set.
Strange.
Cheers, Paul
a value from a super ctor to a this ctor.
class Obj extends Header
{
final Handle handle;
final Mapper mapper;
private Obj(Cache cache, Handle handle, byte[] rawBytes,
int[] dataOffsetHolder)
{
super(cache, rawBytes, dataOffsetHolder);
this.handle = handle;
mapper = buildMapper(rawBytes, dataOffsetHolder[0]);
}
Obj(Cache cache, Handle handle, byte[] rawBytes)
{
this(cache, handle, rawBytes, new int[1]);
}
...
}
The problem was to retrieve an integer value from the super ctor. There's
no room to define a local temporary int[] variable before calling super,
because super() must be the first statement. But you can get a named
temporary int[] variable at the very beginning of a ctor by passing it in as
an argument.
The compiler is apparently clever enough to figure out that, despite the
fact that the second ctor doesn't set the final variables, they will
nevertheless be set by the ctor called with this().
However, if you rearrange things slightly:
private Obj(Cache cache, byte[] rawBytes, int[] dataOffsetHolder)
{
super(cache, rawBytes, dataOffsetHolder);
mapper = buildMapper(rawBytes, dataOffsetHolder[0]);
}
Obj(Cache cache, Handle handle, byte[] rawBytes)
{
this(cache, rawBytes, new int[1]);
this.handle = handle;
}
The compiler now reports two errors relating to whether handle has been set.
Strange.
Cheers, Paul