Java Docs: use instanceof with name binding (#2087)

* Java Docs: use instanceof with name binding

* remove changes in generated code

* Update docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer2.java

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* merge issue

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
PJ Fanning 2025-08-25 13:45:13 +01:00 committed by GitHub
parent 18d7ff815a
commit 56470a4569
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 60 additions and 76 deletions

View file

@ -48,8 +48,8 @@ public class TwoPhaseSetSerializer extends AbstractSerializationSupport {
@Override @Override
public byte[] toBinary(Object obj) { public byte[] toBinary(Object obj) {
if (obj instanceof TwoPhaseSet) { if (obj instanceof TwoPhaseSet tps) {
return twoPhaseSetToProto((TwoPhaseSet) obj).toByteArray(); return twoPhaseSetToProto(tps).toByteArray();
} else { } else {
throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass()); throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass());
} }

View file

@ -49,8 +49,8 @@ public class TwoPhaseSetSerializer2 extends AbstractSerializationSupport {
@Override @Override
public byte[] toBinary(Object obj) { public byte[] toBinary(Object obj) {
if (obj instanceof TwoPhaseSet) { if (obj instanceof TwoPhaseSet tps) {
return twoPhaseSetToProto((TwoPhaseSet) obj).toByteArray(); return twoPhaseSetToProto(tps).toByteArray();
} else { } else {
throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass()); throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass());
} }

View file

@ -24,8 +24,8 @@ public class TwoPhaseSetSerializerWithCompression extends TwoPhaseSetSerializer
// #compression // #compression
@Override @Override
public byte[] toBinary(Object obj) { public byte[] toBinary(Object obj) {
if (obj instanceof TwoPhaseSet) { if (obj instanceof TwoPhaseSet tps) {
return compress(twoPhaseSetToProto((TwoPhaseSet) obj)); return compress(twoPhaseSetToProto(tps));
} else { } else {
throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass()); throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass());
} }

View file

@ -67,8 +67,8 @@ public class EchoManager extends AbstractActor {
.match( .match(
Tcp.CommandFailed.class, Tcp.CommandFailed.class,
failed -> { failed -> {
if (failed.cmd() instanceof Bind) { if (failed.cmd() instanceof Bind bind) {
log.warning("cannot bind to [{}]", ((Bind) failed.cmd()).localAddress()); log.warning("cannot bind to [{}]", bind.localAddress());
getContext().stop(getSelf()); getContext().stop(getSelf());
} else { } else {
log.warning("unknown command failed [{}]", failed.cmd()); log.warning("unknown command failed [{}]", failed.cmd());

View file

@ -236,11 +236,9 @@ public class LambdaPersistenceDocTest {
} }
void updateState(Object event) { void updateState(Object event) {
if (event instanceof MsgSent) { if (event instanceof MsgSent evt) {
final MsgSent evt = (MsgSent) event;
deliver(destination, deliveryId -> new Msg(deliveryId, evt.s)); deliver(destination, deliveryId -> new Msg(deliveryId, evt.s));
} else if (event instanceof MsgConfirmed) { } else if (event instanceof MsgConfirmed evt) {
final MsgConfirmed evt = (MsgConfirmed) event;
confirmDelivery(evt.deliveryId); confirmDelivery(evt.deliveryId);
} }
} }

View file

@ -117,8 +117,7 @@ public class PersistenceQueryDocTest {
*/ */
@Override @Override
public Source<EventEnvelope, NotUsed> eventsByTag(String tag, Offset offset) { public Source<EventEnvelope, NotUsed> eventsByTag(String tag, Offset offset) {
if (offset instanceof Sequence) { if (offset instanceof Sequence sequenceOffset) {
Sequence sequenceOffset = (Sequence) offset;
return Source.fromGraph( return Source.fromGraph(
new MyEventsByTagSource(conn, tag, sequenceOffset.value(), refreshInterval)); new MyEventsByTagSource(conn, tag, sequenceOffset.value(), refreshInterval));
} else if (offset == NoOffset.getInstance()) } else if (offset == NoOffset.getInstance())

View file

@ -101,8 +101,7 @@ public class PersistenceSchemaEvolutionDocTest {
@Override @Override
public byte[] toBinary(Object o) { public byte[] toBinary(Object o) {
if (o instanceof SeatReserved) { if (o instanceof SeatReserved s) {
SeatReserved s = (SeatReserved) o;
return FlightAppModels.SeatReserved.newBuilder() return FlightAppModels.SeatReserved.newBuilder()
.setRow(s.row) .setRow(s.row)
.setLetter(s.letter) .setLetter(s.letter)
@ -153,8 +152,7 @@ public class PersistenceSchemaEvolutionDocTest {
@Override @Override
public EventSeq fromJournal(Object event, String manifest) { public EventSeq fromJournal(Object event, String manifest) {
if (event instanceof JsObject) { if (event instanceof JsObject json) {
JsObject json = (JsObject) event;
if (V1.equals(manifest)) json = rename(json, "code", "seatNr"); if (V1.equals(manifest)) json = rename(json, "code", "seatNr");
return EventSeq.single(json); return EventSeq.single(json);
} else { } else {
@ -217,8 +215,7 @@ public class PersistenceSchemaEvolutionDocTest {
// serialize the object // serialize the object
@Override @Override
public byte[] toBinary(Object obj) { public byte[] toBinary(Object obj) {
if (obj instanceof Person) { if (obj instanceof Person p) {
Person p = (Person) obj;
return (p.name + "|" + p.surname).getBytes(utf8); return (p.name + "|" + p.surname).getBytes(utf8);
} else { } else {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -312,8 +309,7 @@ public class PersistenceSchemaEvolutionDocTest {
@Override @Override
public EventSeq fromJournal(Object event, String manifest) { public EventSeq fromJournal(Object event, String manifest) {
if (event instanceof UserDetailsChanged) { if (event instanceof UserDetailsChanged c) {
UserDetailsChanged c = (UserDetailsChanged) event;
if (c.name == null) return EventSeq.single(new UserAddressChanged(c.address)); if (c.name == null) return EventSeq.single(new UserAddressChanged(c.address));
else if (c.address == null) return EventSeq.single(new UserNameChanged(c.name)); else if (c.address == null) return EventSeq.single(new UserNameChanged(c.name));
else return EventSeq.create(new UserNameChanged(c.name), new UserAddressChanged(c.address)); else return EventSeq.create(new UserNameChanged(c.name), new UserAddressChanged(c.address));
@ -426,8 +422,7 @@ public class PersistenceSchemaEvolutionDocTest {
@Override @Override
public byte[] toBinary(Object o) { public byte[] toBinary(Object o) {
if (o instanceof SamplePayload) { if (o instanceof SamplePayload s) {
SamplePayload s = (SamplePayload) o;
return s.payload.toString().getBytes(utf8); return s.payload.toString().getBytes(utf8);
} else { } else {
// previously also handled "old" events here. // previously also handled "old" events here.
@ -511,8 +506,7 @@ public class PersistenceSchemaEvolutionDocTest {
@Override @Override
public Object toJournal(Object event) { public Object toJournal(Object event) {
if (event instanceof SeatBooked) { if (event instanceof SeatBooked s) {
SeatBooked s = (SeatBooked) event;
return new SeatBookedData(s.code, s.customer.name); return new SeatBookedData(s.code, s.customer.name);
} else { } else {
throw new IllegalArgumentException("Unsupported: " + event.getClass()); throw new IllegalArgumentException("Unsupported: " + event.getClass());
@ -521,8 +515,7 @@ public class PersistenceSchemaEvolutionDocTest {
@Override @Override
public EventSeq fromJournal(Object event, String manifest) { public EventSeq fromJournal(Object event, String manifest) {
if (event instanceof SeatBookedData) { if (event instanceof SeatBookedData d) {
SeatBookedData d = (SeatBookedData) event;
return EventSeq.single(new SeatBooked(d.code, new Customer(d.customerName))); return EventSeq.single(new SeatBooked(d.code, new Customer(d.customerName)));
} else { } else {
throw new IllegalArgumentException("Unsupported: " + event.getClass()); throw new IllegalArgumentException("Unsupported: " + event.getClass());
@ -551,8 +544,7 @@ public class PersistenceSchemaEvolutionDocTest {
@Override @Override
public EventSeq fromJournal(Object event, String manifest) { public EventSeq fromJournal(Object event, String manifest) {
if (event instanceof JsObject) { if (event instanceof JsObject json) {
JsObject json = (JsObject) event;
return EventSeq.single(marshaller.fromJson(json)); return EventSeq.single(marshaller.fromJson(json));
} else { } else {
throw new IllegalArgumentException( throw new IllegalArgumentException(

View file

@ -74,8 +74,7 @@ public class LeveldbPersistenceQueryDocTest {
@Override @Override
public Object toJournal(Object event) { public Object toJournal(Object event) {
if (event instanceof String) { if (event instanceof String s) {
String s = (String) event;
Set<String> tags = new HashSet<String>(); Set<String> tags = new HashSet<String>();
if (s.contains("green")) tags.add("green"); if (s.contains("green")) tags.add("green");
if (s.contains("black")) tags.add("black"); if (s.contains("black")) tags.add("black");

View file

@ -43,8 +43,7 @@ public class TestKitExamples {
// if you return ProcessingSuccess the operation will be performed, otherwise not. // if you return ProcessingSuccess the operation will be performed, otherwise not.
if (count < 10) { if (count < 10) {
count += 1; count += 1;
if (processingUnit instanceof ReadEvents) { if (processingUnit instanceof ReadEvents read) {
ReadEvents read = (ReadEvents) processingUnit;
if (read.batch().nonEmpty()) { if (read.batch().nonEmpty()) {
ProcessingSuccess.getInstance(); ProcessingSuccess.getInstance();
} else { } else {
@ -79,8 +78,7 @@ public class TestKitExamples {
// if you return ProcessingSuccess the operation will be performed, otherwise not. // if you return ProcessingSuccess the operation will be performed, otherwise not.
if (count < 10) { if (count < 10) {
count += 1; count += 1;
if (processingUnit instanceof ReadSnapshot) { if (processingUnit instanceof ReadSnapshot read) {
ReadSnapshot read = (ReadSnapshot) processingUnit;
if (read.getSnapshot().isPresent()) { if (read.getSnapshot().isPresent()) {
ProcessingSuccess.getInstance(); ProcessingSuccess.getInstance();
} else { } else {

View file

@ -135,8 +135,8 @@ public class ConsistentHashingRouterDocTest extends AbstractJavaTest {
new ConsistentHashMapper() { new ConsistentHashMapper() {
@Override @Override
public Object hashKey(Object message) { public Object hashKey(Object message) {
if (message instanceof Evict) { if (message instanceof Evict evict) {
return ((Evict) message).key; return evict.key;
} else { } else {
return null; return null;
} }

View file

@ -91,7 +91,7 @@ public class CustomRouterDocTest extends AbstractJavaTest {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
return (obj instanceof TestRoutee) && n == ((TestRoutee) obj).n; return (obj instanceof TestRoutee routee) && n == routee.n;
} }
} }

View file

@ -116,8 +116,8 @@ public class SerializationDocTest {
@Override @Override
public byte[] toBinary(Object obj) { public byte[] toBinary(Object obj) {
// Put the real code that serializes the object here // Put the real code that serializes the object here
if (obj instanceof Customer) return ((Customer) obj).name.getBytes(UTF_8); if (obj instanceof Customer customer) return customer.name.getBytes(UTF_8);
else if (obj instanceof User) return ((User) obj).name.getBytes(UTF_8); else if (obj instanceof User user) return user.name.getBytes(UTF_8);
else throw new IllegalArgumentException("Unknown type: " + obj); else throw new IllegalArgumentException("Unknown type: " + obj);
} }

View file

@ -54,28 +54,28 @@ public class ClusterShardingTest {
@Override @Override
public String entityId(Object message) { public String entityId(Object message) {
if (message instanceof Counter.EntityEnvelope) if (message instanceof Counter.EntityEnvelope envelope)
return String.valueOf(((Counter.EntityEnvelope) message).id); return String.valueOf(envelope.id);
else if (message instanceof Counter.Get) else if (message instanceof Counter.Get get)
return String.valueOf(((Counter.Get) message).counterId); return String.valueOf(get.counterId);
else return null; else return null;
} }
@Override @Override
public Object entityMessage(Object message) { public Object entityMessage(Object message) {
if (message instanceof Counter.EntityEnvelope) if (message instanceof Counter.EntityEnvelope envelope)
return ((Counter.EntityEnvelope) message).payload; return envelope.payload;
else return message; else return message;
} }
@Override @Override
public String shardId(Object message) { public String shardId(Object message) {
int numberOfShards = 100; int numberOfShards = 100;
if (message instanceof Counter.EntityEnvelope) { if (message instanceof Counter.EntityEnvelope envelope) {
long id = ((Counter.EntityEnvelope) message).id; long id = envelope.id;
return String.valueOf(id % numberOfShards); return String.valueOf(id % numberOfShards);
} else if (message instanceof Counter.Get) { } else if (message instanceof Counter.Get get) {
long id = ((Counter.Get) message).counterId; long id = get.counterId;
return String.valueOf(id % numberOfShards); return String.valueOf(id % numberOfShards);
} else { } else {
return null; return null;
@ -123,17 +123,17 @@ public class ClusterShardingTest {
@Override @Override
public String entityId(Object message) { public String entityId(Object message) {
if (message instanceof Counter.EntityEnvelope) if (message instanceof Counter.EntityEnvelope envelope)
return String.valueOf(((Counter.EntityEnvelope) message).id); return String.valueOf(envelope.id);
else if (message instanceof Counter.Get) else if (message instanceof Counter.Get get)
return String.valueOf(((Counter.Get) message).counterId); return String.valueOf(get.counterId);
else return null; else return null;
} }
@Override @Override
public Object entityMessage(Object message) { public Object entityMessage(Object message) {
if (message instanceof Counter.EntityEnvelope) if (message instanceof Counter.EntityEnvelope envelope)
return ((Counter.EntityEnvelope) message).payload; return envelope.payload;
else return message; else return message;
} }
@ -141,14 +141,14 @@ public class ClusterShardingTest {
@Override @Override
public String shardId(Object message) { public String shardId(Object message) {
int numberOfShards = 100; int numberOfShards = 100;
if (message instanceof Counter.EntityEnvelope) { if (message instanceof Counter.EntityEnvelope envelope) {
long id = ((Counter.EntityEnvelope) message).id; long id = envelope.id;
return String.valueOf(id % numberOfShards); return String.valueOf(id % numberOfShards);
} else if (message instanceof Counter.Get) { } else if (message instanceof Counter.Get get) {
long id = ((Counter.Get) message).counterId; long id = get.counterId;
return String.valueOf(id % numberOfShards); return String.valueOf(id % numberOfShards);
} else if (message instanceof ShardRegion.StartEntity) { } else if (message instanceof ShardRegion.StartEntity entity) {
long id = Long.valueOf(((ShardRegion.StartEntity) message).entityId()); long id = Long.valueOf(entity.entityId());
return String.valueOf(id % numberOfShards); return String.valueOf(id % numberOfShards);
} else { } else {
return null; return null;

View file

@ -64,8 +64,8 @@ public class BidiFlowDocTest extends AbstractJavaTest {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof Ping) { if (o instanceof Ping ping) {
return ((Ping) o).id == id; return ping.id == id;
} else return false; } else return false;
} }
@ -84,8 +84,8 @@ public class BidiFlowDocTest extends AbstractJavaTest {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof Pong) { if (o instanceof Pong pong) {
return ((Pong) o).id == id; return pong.id == id;
} else return false; } else return false;
} }
@ -98,8 +98,8 @@ public class BidiFlowDocTest extends AbstractJavaTest {
// #codec-impl // #codec-impl
public static ByteString toBytes(Message msg) { public static ByteString toBytes(Message msg) {
// #implementation-details-elided // #implementation-details-elided
if (msg instanceof Ping) { if (msg instanceof Ping ping) {
final int id = ((Ping) msg).id; final int id = ping.id;
return new ByteStringBuilder().putByte((byte) 1).putInt(id, ByteOrder.LITTLE_ENDIAN).result(); return new ByteStringBuilder().putByte((byte) 1).putInt(id, ByteOrder.LITTLE_ENDIAN).result();
} else { } else {
final int id = ((Pong) msg).id; final int id = ((Pong) msg).id;

View file

@ -803,8 +803,7 @@ public class IntegrationDocTest extends AbstractJavaTest {
System.out.println("enqueued " + x); System.out.println("enqueued " + x);
} else if (result == QueueOfferResult.dropped()) { } else if (result == QueueOfferResult.dropped()) {
System.out.println("dropped " + x); System.out.println("dropped " + x);
} else if (result instanceof QueueOfferResult.Failure) { } else if (result instanceof QueueOfferResult.Failure failure) {
QueueOfferResult.Failure failure = (QueueOfferResult.Failure) result;
System.out.println("Offer failed " + failure.cause().getMessage()); System.out.println("Offer failed " + failure.cause().getMessage());
} else if (result instanceof QueueOfferResult.QueueClosed$) { } else if (result instanceof QueueOfferResult.QueueClosed$) {
System.out.println("Bounded Source Queue closed"); System.out.println("Bounded Source Queue closed");

View file

@ -34,11 +34,10 @@ public class Monitor {
private static <T> void printMonitorState(FlowMonitorState.StreamState<T> state) { private static <T> void printMonitorState(FlowMonitorState.StreamState<T> state) {
if (state == FlowMonitorState.finished()) { if (state == FlowMonitorState.finished()) {
System.out.println("Stream is initialized but hasn't processed any element"); System.out.println("Stream is initialized but hasn't processed any element");
} else if (state instanceof FlowMonitorState.Received) { } else if (state instanceof FlowMonitorState.Received received) {
FlowMonitorState.Received msg = (FlowMonitorState.Received) state; System.out.println("Last message received: " + received.msg());
System.out.println("Last message received: " + msg.msg()); } else if (state instanceof FlowMonitorState.Failed failed) {
} else if (state instanceof FlowMonitorState.Failed) { Throwable cause = failed.cause();
Throwable cause = ((FlowMonitorState.Failed) state).cause();
System.out.println("Stream failed with cause: " + cause.getMessage()); System.out.println("Stream failed with cause: " + cause.getMessage());
} else { } else {
System.out.println("Stream completed already"); System.out.println("Stream completed already");