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) { public static @NotNull ServerPacket createSoundPacket(@NotNull Sound sound, Sound.@NotNull Emitter emitter) {
if (emitter == Sound.Emitter.self()) if (emitter == Sound.Emitter.self())
throw new IllegalArgumentException("you must replace instances of Emitter.self() before calling this method"); 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"); throw new IllegalArgumentException("you can only call this method with entities");
final Entity entity = (Entity) emitter;
final SoundEvent minestomSound = SoundEvent.fromNamespaceId(sound.name().asString()); final SoundEvent minestomSound = SoundEvent.fromNamespaceId(sound.name().asString());
if (minestomSound != null) { if (minestomSound != null) {

View File

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

View File

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

View File

@ -16,8 +16,7 @@ public enum EntitySpawnType {
packet.uuid = entity.getUuid(); packet.uuid = entity.getUuid();
packet.type = entity.getEntityType().id(); packet.type = entity.getEntityType().id();
packet.position = entity.getPosition(); packet.position = entity.getPosition();
if (entity.getEntityMeta() instanceof ObjectDataProvider) { if (entity.getEntityMeta() instanceof ObjectDataProvider objectDataProvider) {
ObjectDataProvider objectDataProvider = (ObjectDataProvider) entity.getEntityMeta();
packet.data = objectDataProvider.getObjectData(); packet.data = objectDataProvider.getObjectData();
if (objectDataProvider.requiresVelocityPacketAtSpawn()) { if (objectDataProvider.requiresVelocityPacketAtSpawn()) {
final var velocity = entity.getVelocityForPacket(); final var velocity = entity.getVelocityForPacket();
@ -57,8 +56,7 @@ public enum EntitySpawnType {
SpawnExperienceOrbPacket packet = new SpawnExperienceOrbPacket(); SpawnExperienceOrbPacket packet = new SpawnExperienceOrbPacket();
packet.entityId = entity.getEntityId(); packet.entityId = entity.getEntityId();
packet.position = entity.getPosition(); packet.position = entity.getPosition();
if (entity.getEntityMeta() instanceof ExperienceOrbMeta) { if (entity.getEntityMeta() instanceof ExperienceOrbMeta experienceOrbMeta) {
ExperienceOrbMeta experienceOrbMeta = (ExperienceOrbMeta) entity.getEntityMeta();
packet.expCount = (short) experienceOrbMeta.getCount(); packet.expCount = (short) experienceOrbMeta.getCount();
} }
return packet; return packet;
@ -70,8 +68,7 @@ public enum EntitySpawnType {
SpawnPaintingPacket packet = new SpawnPaintingPacket(); SpawnPaintingPacket packet = new SpawnPaintingPacket();
packet.entityId = entity.getEntityId(); packet.entityId = entity.getEntityId();
packet.entityUuid = entity.getUuid(); packet.entityUuid = entity.getUuid();
if (entity.getEntityMeta() instanceof PaintingMeta) { if (entity.getEntityMeta() instanceof PaintingMeta paintingMeta) {
PaintingMeta paintingMeta = (PaintingMeta) entity.getEntityMeta();
packet.motive = paintingMeta.getMotive().ordinal(); packet.motive = paintingMeta.getMotive().ordinal();
packet.position = new Vec( packet.position = new Vec(
Math.max(0, (paintingMeta.getMotive().getWidth() >> 1) - 1), 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)); sendPacketToViewersAndSelf(new EntityAnimationPacket(getEntityId(), EntityAnimationPacket.Animation.TAKE_DAMAGE));
// Additional hearts support // Additional hearts support
if (this instanceof Player) { if (this instanceof Player player) {
final Player player = (Player) this;
final float additionalHearts = player.getAdditionalHearts(); final float additionalHearts = player.getAdditionalHearts();
if (additionalHearts > 0) { if (additionalHearts > 0) {
if (remainingDamage > additionalHearts) { if (remainingDamage > additionalHearts) {
@ -476,8 +475,7 @@ public class LivingEntity extends Entity implements EquipmentHandler {
protected void onAttributeChanged(@NotNull AttributeInstance attributeInstance) { protected void onAttributeChanged(@NotNull AttributeInstance attributeInstance) {
if (attributeInstance.getAttribute().isShared()) { if (attributeInstance.getAttribute().isShared()) {
boolean self = false; boolean self = false;
if (this instanceof Player) { if (this instanceof Player player) {
Player player = (Player) this;
PlayerConnection playerConnection = player.playerConnection; PlayerConnection playerConnection = player.playerConnection;
// connection null during Player initialization (due to #super call) // connection null during Player initialization (due to #super call)
self = playerConnection != null && playerConnection.getConnectionState() == ConnectionState.PLAY; self = playerConnection != null && playerConnection.getConnectionState() == ConnectionState.PLAY;
@ -681,20 +679,10 @@ public class LivingEntity extends Entity implements EquipmentHandler {
*/ */
public void setTeam(Team team) { public void setTeam(Team team) {
if (this.team == team) return; if (this.team == team) return;
String member = this instanceof Player player ? player.getUsername() : uuid.toString();
String member;
if (this instanceof Player) {
Player player = (Player) this;
member = player.getUsername();
} else {
member = this.uuid.toString();
}
if (this.team != null) { if (this.team != null) {
this.team.removeMember(member); this.team.removeMember(member);
} }
this.team = team; this.team = team;
if (team != null) { if (team != null) {
team.addMember(member); team.addMember(member);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -31,10 +31,8 @@ public class LoginPluginResponsePacket implements ClientPreplayPacket {
@Override @Override
public void process(@NotNull PlayerConnection connection) { public void process(@NotNull PlayerConnection connection) {
// Proxy support // Proxy support
if (connection instanceof PlayerSocketConnection) { if (connection instanceof PlayerSocketConnection socketConnection) {
final PlayerSocketConnection socketConnection = (PlayerSocketConnection) connection;
final String channel = socketConnection.getPluginRequestChannel(messageId); final String channel = socketConnection.getPluginRequestChannel(messageId);
if (channel != null) { if (channel != null) {
boolean success = false; 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) -> { public static final Tag<String> SNBT = new Tag<>(null, NBTCompound::toSNBT, (original, snbt) -> {
try { try {
final var updated = new SNBTParser(new StringReader(snbt)).parse(); 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!"); throw new IllegalArgumentException("'" + snbt + "' is not a compound!");
NBTCompound updatedCompound = (NBTCompound) updated;
original.clear(); original.clear();
updatedCompound.getKeys().forEach(s -> updatedCompound.getKeys().forEach(s ->
original.set(s, Objects.requireNonNull(updatedCompound.get(s)))); original.set(s, Objects.requireNonNull(updatedCompound.get(s))));

View File

@ -103,9 +103,8 @@ public class NamespaceID implements CharSequence, Key {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if(this == o) return true; if (this == o) return true;
if(!(o instanceof Key)) return false; if (!(o instanceof final Key that)) return false;
final Key that = (Key) o;
return Objects.equals(this.domain, that.namespace()) && Objects.equals(this.path, that.value()); 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}. * Simple implementation of {@link NamedAndIdentified}.
*
* @see #of(String, UUID) * @see #of(String, UUID)
* @see #of(Component, UUID) * @see #of(Component, UUID)
*/ */
@ -51,8 +52,7 @@ class NamedAndIdentifiedImpl implements NamedAndIdentified {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof NamedAndIdentified)) return false; if (!(o instanceof NamedAndIdentified that)) return false;
NamedAndIdentified that = (NamedAndIdentified) o;
return this.uuid.equals(that.getUuid()); return this.uuid.equals(that.getUuid());
} }

View File

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