Use more instanceof pattern matching

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2021-10-22 02:19:38 +02:00
parent 5030664ff9
commit 7891cc5bbe
17 changed files with 28 additions and 76 deletions

View File

@ -141,10 +141,9 @@ public class AdventurePacketConvertor {
public static @NotNull ServerPacket createSoundPacket(@NotNull Sound sound, Sound.@NotNull Emitter emitter) {
if (emitter == Sound.Emitter.self())
throw new IllegalArgumentException("you must replace instances of Emitter.self() before calling this method");
if (!(emitter instanceof Entity))
if (!(emitter instanceof Entity entity))
throw new IllegalArgumentException("you can only call this method with entities");
final Entity entity = (Entity) emitter;
final SoundEvent minestomSound = SoundEvent.fromNamespaceId(sound.name().asString());
if (minestomSound != null) {

View File

@ -1,7 +1,5 @@
package net.minestom.server.adventure.provider;
import java.util.UUID;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.nbt.api.BinaryTagHolder;
import net.kyori.adventure.text.Component;
@ -17,6 +15,7 @@ import org.jglrxavpok.hephaistos.nbt.NBTException;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;
final class NBTLegacyHoverEventSerializer implements LegacyHoverEventSerializer {
static final NBTLegacyHoverEventSerializer INSTANCE = new NBTLegacyHoverEventSerializer();
@ -33,8 +32,8 @@ final class NBTLegacyHoverEventSerializer implements LegacyHoverEventSerializer
try {
// attempt the parse
final NBT nbt = MinestomAdventure.NBT_CODEC.decode(raw);
if (!(nbt instanceof NBTCompound)) throw new IOException("contents were not a compound");
final NBTCompound contents = (NBTCompound) nbt, tag = contents.getCompound(ITEM_TAG);
if (!(nbt instanceof NBTCompound contents)) throw new IOException("contents were not a compound");
final NBTCompound tag = contents.getCompound(ITEM_TAG);
// create the event
return HoverEvent.ShowItem.of(
@ -53,9 +52,7 @@ final class NBTLegacyHoverEventSerializer implements LegacyHoverEventSerializer
try {
final NBT nbt = MinestomAdventure.NBT_CODEC.decode(raw);
if (!(nbt instanceof NBTCompound)) throw new IOException("contents were not a compound");
final NBTCompound contents = (NBTCompound) nbt;
if (!(nbt instanceof NBTCompound contents)) throw new IOException("contents were not a compound");
return HoverEvent.ShowEntity.of(
Key.key(Objects.requireNonNullElse(contents.getString(ENTITY_TYPE), "")),

View File

@ -100,8 +100,7 @@ public final class CommandManager {
*/
public @NotNull CommandResult execute(@NotNull CommandSender sender, @NotNull String command) {
// Command event
if (sender instanceof Player) {
final Player player = (Player) sender;
if (sender instanceof Player player) {
PlayerCommandEvent playerCommandEvent = new PlayerCommandEvent(player, command);
EventDispatcher.call(playerCommandEvent);
if (playerCommandEvent.isCancelled())

View File

@ -367,10 +367,8 @@ public class Command {
node = findNode.apply(node, Collections.singleton(literal));
continue;
} else if (argument instanceof ArgumentWord) {
ArgumentWord argumentWord = (ArgumentWord) argument;
} else if (argument instanceof ArgumentWord argumentWord) {
if (argumentWord.hasRestrictions()) {
addArguments.accept(node, arguments);
arguments = new ArrayList<>();

View File

@ -16,8 +16,7 @@ public enum EntitySpawnType {
packet.uuid = entity.getUuid();
packet.type = entity.getEntityType().id();
packet.position = entity.getPosition();
if (entity.getEntityMeta() instanceof ObjectDataProvider) {
ObjectDataProvider objectDataProvider = (ObjectDataProvider) entity.getEntityMeta();
if (entity.getEntityMeta() instanceof ObjectDataProvider objectDataProvider) {
packet.data = objectDataProvider.getObjectData();
if (objectDataProvider.requiresVelocityPacketAtSpawn()) {
final var velocity = entity.getVelocityForPacket();
@ -57,8 +56,7 @@ public enum EntitySpawnType {
SpawnExperienceOrbPacket packet = new SpawnExperienceOrbPacket();
packet.entityId = entity.getEntityId();
packet.position = entity.getPosition();
if (entity.getEntityMeta() instanceof ExperienceOrbMeta) {
ExperienceOrbMeta experienceOrbMeta = (ExperienceOrbMeta) entity.getEntityMeta();
if (entity.getEntityMeta() instanceof ExperienceOrbMeta experienceOrbMeta) {
packet.expCount = (short) experienceOrbMeta.getCount();
}
return packet;
@ -70,8 +68,7 @@ public enum EntitySpawnType {
SpawnPaintingPacket packet = new SpawnPaintingPacket();
packet.entityId = entity.getEntityId();
packet.entityUuid = entity.getUuid();
if (entity.getEntityMeta() instanceof PaintingMeta) {
PaintingMeta paintingMeta = (PaintingMeta) entity.getEntityMeta();
if (entity.getEntityMeta() instanceof PaintingMeta paintingMeta) {
packet.motive = paintingMeta.getMotive().ordinal();
packet.position = new Vec(
Math.max(0, (paintingMeta.getMotive().getWidth() >> 1) - 1),

View File

@ -354,8 +354,7 @@ public class LivingEntity extends Entity implements EquipmentHandler {
sendPacketToViewersAndSelf(new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.TAKE_DAMAGE));
// Additional hearts support
if (this instanceof Player) {
final Player player = (Player) this;
if (this instanceof Player player) {
final float additionalHearts = player.getAdditionalHearts();
if (additionalHearts > 0) {
if (remainingDamage > additionalHearts) {
@ -476,8 +475,7 @@ public class LivingEntity extends Entity implements EquipmentHandler {
protected void onAttributeChanged(@NotNull AttributeInstance attributeInstance) {
if (attributeInstance.getAttribute().isShared()) {
boolean self = false;
if (this instanceof Player) {
Player player = (Player) this;
if (this instanceof Player player) {
PlayerConnection playerConnection = player.playerConnection;
// connection null during Player initialization (due to #super call)
self = playerConnection != null && playerConnection.getConnectionState() == ConnectionState.PLAY;
@ -681,20 +679,10 @@ public class LivingEntity extends Entity implements EquipmentHandler {
*/
public void setTeam(Team team) {
if (this.team == team) return;
String member;
if (this instanceof Player) {
Player player = (Player) this;
member = player.getUsername();
} else {
member = this.uuid.toString();
}
String member = this instanceof Player player ? player.getUsername() : uuid.toString();
if (this.team != null) {
this.team.removeMember(member);
}
this.team = team;
if (team != null) {
team.addMember(member);

View File

@ -22,20 +22,15 @@ public class LastEntityDamagerTarget extends TargetSelector {
@Override
public Entity findTarget() {
final DamageType damageType = entityCreature.getLastDamageSource();
if (!(damageType instanceof EntityDamage)) {
if (!(damageType instanceof EntityDamage entityDamage)) {
// No damager recorded, return null
return null;
}
final EntityDamage entityDamage = (EntityDamage) damageType;
final Entity entity = entityDamage.getSource();
if (entity.isRemoved()) {
// Entity not valid
return null;
}
// Check range
return entityCreature.getDistance(entity) < range ? entity : null;
}

View File

@ -621,13 +621,12 @@ public class ExtensionManager {
*/
private void setupCodeModifiers(@NotNull List<DiscoveredExtension> extensions) {
final ClassLoader cl = getClass().getClassLoader();
if (!(cl instanceof MinestomRootClassLoader)) {
if (!(cl instanceof MinestomRootClassLoader modifiableClassLoader)) {
LOGGER.warn("Current class loader is not a MinestomOverwriteClassLoader, but {}. " +
"This disables code modifiers (Mixin support is therefore disabled). " +
"This can be fixed by starting your server using Bootstrap#bootstrap (optional).", cl);
return;
}
MinestomRootClassLoader modifiableClassLoader = (MinestomRootClassLoader) cl;
setupCodeModifiers(extensions, modifiableClassLoader);
}

View File

@ -121,11 +121,8 @@ public class BlockPlacementListener {
entity.getEntityType() == EntityType.ITEM)
continue;
// Marker Armor Stands should not prevent block placement
if (entity.getEntityMeta() instanceof ArmorStandMeta) {
ArmorStandMeta armorStandMeta = (ArmorStandMeta) entity.getEntityMeta();
if (armorStandMeta.isMarker()) {
continue;
}
if (entity.getEntityMeta() instanceof ArmorStandMeta armorStandMeta) {
if (armorStandMeta.isMarker()) continue;
}
intersect = entity.getBoundingBox().intersectWithBlock(placementPosition);
if (intersect)

View File

@ -1,12 +1,12 @@
package net.minestom.server.listener;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.Player;
import net.minestom.server.entity.metadata.other.BoatMeta;
import net.minestom.server.network.packet.client.play.ClientSteerBoatPacket;
import net.minestom.server.network.packet.client.play.ClientSteerVehiclePacket;
import net.minestom.server.network.packet.client.play.ClientVehicleMovePacket;
import net.minestom.server.coordinate.Pos;
public class PlayerVehicleListener {
@ -38,10 +38,7 @@ public class PlayerVehicleListener {
public static void boatSteerListener(ClientSteerBoatPacket packet, Player player) {
final Entity vehicle = player.getVehicle();
if (!(vehicle.getEntityMeta() instanceof BoatMeta))
return;
BoatMeta boat = (BoatMeta) vehicle.getEntityMeta();
if (!(vehicle.getEntityMeta() instanceof BoatMeta boat)) return;
boat.setLeftPaddleTurning(packet.leftPaddleTurning);
boat.setRightPaddleTurning(packet.rightPaddleTurning);
}

View File

@ -61,9 +61,7 @@ public class HandshakePacket implements ClientPreplayPacket {
public void process(@NotNull PlayerConnection connection) {
// Bungee support (IP forwarding)
if (BungeeCordProxy.isEnabled() && connection instanceof PlayerSocketConnection) {
PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
if (BungeeCordProxy.isEnabled() && connection instanceof PlayerSocketConnection socketConnection) {
if (serverAddress != null) {
final String[] split = serverAddress.split("\00");

View File

@ -39,10 +39,7 @@ public class EncryptionResponsePacket implements ClientPreplayPacket {
@Override
public void process(@NotNull PlayerConnection connection) {
// Encryption is only support for socket connection
if (!(connection instanceof PlayerSocketConnection)) {
return;
}
final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
if (!(connection instanceof PlayerSocketConnection socketConnection)) return;
AsyncUtils.runAsync(() -> {
final String loginUsername = socketConnection.getLoginUsername();
if (loginUsername == null || loginUsername.isEmpty()) {

View File

@ -31,10 +31,8 @@ public class LoginPluginResponsePacket implements ClientPreplayPacket {
@Override
public void process(@NotNull PlayerConnection connection) {
// Proxy support
if (connection instanceof PlayerSocketConnection) {
final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
if (connection instanceof PlayerSocketConnection socketConnection) {
final String channel = socketConnection.getPluginRequestChannel(messageId);
if (channel != null) {
boolean success = false;

View File

@ -34,9 +34,8 @@ public class Tag<T> {
public static final Tag<String> SNBT = new Tag<>(null, NBTCompound::toSNBT, (original, snbt) -> {
try {
final var updated = new SNBTParser(new StringReader(snbt)).parse();
if (!(updated instanceof NBTCompound))
if (!(updated instanceof NBTCompound updatedCompound))
throw new IllegalArgumentException("'" + snbt + "' is not a compound!");
NBTCompound updatedCompound = (NBTCompound) updated;
original.clear();
updatedCompound.getKeys().forEach(s ->
original.set(s, Objects.requireNonNull(updatedCompound.get(s))));

View File

@ -103,9 +103,8 @@ public class NamespaceID implements CharSequence, Key {
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(!(o instanceof Key)) return false;
final Key that = (Key) o;
if (this == o) return true;
if (!(o instanceof final Key that)) return false;
return Objects.equals(this.domain, that.namespace()) && Objects.equals(this.path, that.value());
}

View File

@ -8,6 +8,7 @@ import java.util.UUID;
/**
* Simple implementation of {@link NamedAndIdentified}.
*
* @see #of(String, UUID)
* @see #of(Component, UUID)
*/
@ -51,8 +52,7 @@ class NamedAndIdentifiedImpl implements NamedAndIdentified {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof NamedAndIdentified)) return false;
NamedAndIdentified that = (NamedAndIdentified) o;
if (!(o instanceof NamedAndIdentified that)) return false;
return this.uuid.equals(that.getUuid());
}

View File

@ -26,10 +26,7 @@ public final class InstanceUtils {
}
// InstanceContainer check (copied from)
if (instance1 instanceof InstanceContainer && instance2 instanceof InstanceContainer) {
final InstanceContainer container1 = (InstanceContainer) instance1;
final InstanceContainer container2 = (InstanceContainer) instance2;
if (instance1 instanceof InstanceContainer container1 && instance2 instanceof InstanceContainer container2) {
if (container1.getSrcInstance() != null) {
return container1.getSrcInstance().equals(container2)
&& container1.getLastBlockChangeTime() == container2.getLastBlockChangeTime();
@ -38,8 +35,6 @@ public final class InstanceUtils {
&& container2.getLastBlockChangeTime() == container1.getLastBlockChangeTime();
}
}
return false;
}