From d7d1303f72793a0d762a22ba8142cf1e8f78bc0a Mon Sep 17 00:00:00 2001 From: Daniil Zao Date: Sat, 29 Jun 2024 01:24:25 +0300 Subject: [PATCH] Clean a bunch of random stuff --- .github/workflows/maven.yml | 5 +- pom.xml | 2 +- src/wgextender/WGExtender.java | 8 ++- src/wgextender/commands/Commands.java | 51 ++++++++---------- .../claimcommand/WGRegionCommandWrapper.java | 24 +++++---- .../features/flags/OldPVPFlagsHandler.java | 44 ++++++++------- .../features/flags/WGExtenderFlags.java | 54 ++++--------------- .../regionprotect/WGOverrideListener.java | 3 +- .../ownormembased/PvPHandlingListener.java | 38 ++++++------- src/wgextender/utils/ReflectionUtils.java | 36 ------------- 10 files changed, 97 insertions(+), 168 deletions(-) delete mode 100644 src/wgextender/utils/ReflectionUtils.java diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 56fbbb4..2f3486d 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -1,9 +1,6 @@ name: Java CI -on: - push: - branches: - - master +on: push jobs: build: diff --git a/pom.xml b/pom.xml index 3eea4ff..99aab6d 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.hurricanegames wgextender - 3.1.1-fork + 3.2.0-fork-SNAPSHOT jar WGExtender diff --git a/src/wgextender/WGExtender.java b/src/wgextender/WGExtender.java index 3c164c8..d7afaae 100644 --- a/src/wgextender/WGExtender.java +++ b/src/wgextender/WGExtender.java @@ -51,6 +51,11 @@ public WGExtender() { private PvPHandlingListener pvplistener; private OldPVPFlagsHandler oldpvphandler; + @Override + public void onLoad() { + WGExtenderFlags.registerFlags(getLogger()); + } + @Override public void onEnable() { VaultIntegration.getInstance().initialize(this); @@ -68,11 +73,10 @@ public void onEnable() { try { WGRegionCommandWrapper.inject(config); WEWandCommandWrapper.inject(config); - WGExtenderFlags.registerFlags(); pvplistener = new PvPHandlingListener(config); pvplistener.inject(); oldpvphandler = new OldPVPFlagsHandler(); - oldpvphandler.start(); + oldpvphandler.start(this); } catch (Throwable t) { getLogger().log(Level.SEVERE, "Unable to inject, shutting down", t); t.printStackTrace(); diff --git a/src/wgextender/commands/Commands.java b/src/wgextender/commands/Commands.java index a3e7cc3..a47310b 100644 --- a/src/wgextender/commands/Commands.java +++ b/src/wgextender/commands/Commands.java @@ -23,18 +23,13 @@ import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.domains.DefaultDomain; import com.sk89q.worldguard.protection.ApplicableRegionSet; -import com.sk89q.worldguard.protection.flags.BooleanFlag; -import com.sk89q.worldguard.protection.flags.EnumFlag; -import com.sk89q.worldguard.protection.flags.Flag; -import com.sk89q.worldguard.protection.flags.Flags; -import com.sk89q.worldguard.protection.flags.StateFlag; +import com.sk89q.worldguard.protection.flags.*; import com.sk89q.worldguard.protection.flags.StateFlag.State; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.command.Command; @@ -48,30 +43,28 @@ import wgextender.utils.WEUtils; import wgextender.utils.WGRegionUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; +import static org.bukkit.ChatColor.BLUE; +import static org.bukkit.ChatColor.RED; import static org.bukkit.util.StringUtil.copyPartialMatches; //TODO: refactor public class Commands implements CommandExecutor, TabCompleter { protected final Config config; + public Commands(Config config) { this.config = config; } - protected static List getRegionsInPlayerSelection(Player player) throws IncompleteRegionException { + private static List getRegionsInPlayerSelection(Player player) throws IncompleteRegionException { Region psel = WEUtils.getSelection(player); ProtectedRegion fakerg = new ProtectedCuboidRegion("wgexfakerg", psel.getMaximumPoint(), psel.getMinimumPoint()); ApplicableRegionSet ars = WGRegionUtils.getRegionManager(player.getWorld()).getApplicableRegions(fakerg); - return - StreamSupport.stream(ars.spliterator(), false) + return StreamSupport.stream(ars.spliterator(), false) .map(ProtectedRegion::getId) .collect(Collectors.toList()); } @@ -79,22 +72,22 @@ protected static List getRegionsInPlayerSelection(Player player) throws @Override public boolean onCommand(CommandSender sender, Command arg1, String label, String[] args) { if (!sender.hasPermission("wgextender.admin")) { - sender.sendMessage(ChatColor.RED+"Недостаточно прав"); + sender.sendMessage(RED + "Недостаточно прав"); return true; } if (args.length >= 1) { switch (args[0].toLowerCase()) { case "help" -> { - sender.sendMessage(ChatColor.BLUE + "wgex reload - перезагрузить конфиг"); - sender.sendMessage(ChatColor.BLUE + "wgex search - ищет регионы в выделенной области"); - sender.sendMessage(ChatColor.BLUE + "wgex setflag {world} {flag} {value} - устанавливает флаг {flag} со значением {value} на все регионы в мире {world}"); - sender.sendMessage(ChatColor.BLUE + "wgex removeowner {name} - удаляет игрока из списков владельцев всех регионов"); - sender.sendMessage(ChatColor.BLUE + "wgex removemember {name} - удаляет игрока из списков членов всех регионов"); + sender.sendMessage(BLUE + "wgex reload - перезагрузить конфиг"); + sender.sendMessage(BLUE + "wgex search - ищет регионы в выделенной области"); + sender.sendMessage(BLUE + "wgex setflag {world} {flag} {value} - устанавливает флаг {flag} со значением {value} на все регионы в мире {world}"); + sender.sendMessage(BLUE + "wgex removeowner {name} - удаляет игрока из списков владельцев всех регионов"); + sender.sendMessage(BLUE + "wgex removemember {name} - удаляет игрока из списков членов всех регионов"); return true; } case "reload" -> { config.loadConfig(); - sender.sendMessage(ChatColor.BLUE + "Конфиг перезагружен"); + sender.sendMessage(BLUE + "Конфиг перезагружен"); return true; } case "search" -> { @@ -102,12 +95,12 @@ public boolean onCommand(CommandSender sender, Command arg1, String label, Strin try { List regions = getRegionsInPlayerSelection(player); if (regions.isEmpty()) { - sender.sendMessage(ChatColor.BLUE + "Регионов пересекающихся с выделенной зоной не найдено"); + sender.sendMessage(BLUE + "Регионов пересекающихся с выделенной зоной не найдено"); } else { - sender.sendMessage(ChatColor.BLUE + "Найдены регионы пересекающиеся с выделенной зоной: " + regions); + sender.sendMessage(BLUE + "Найдены регионы пересекающиеся с выделенной зоной: " + regions); } } catch (IncompleteRegionException e) { - sender.sendMessage(ChatColor.BLUE + "Сначала выделите зону поиска"); + sender.sendMessage(BLUE + "Сначала выделите зону поиска"); } return true; } @@ -119,12 +112,12 @@ public boolean onCommand(CommandSender sender, Command arg1, String label, Strin } World world = Bukkit.getWorld(args[1]); if (world == null) { - sender.sendMessage(ChatColor.BLUE + "Мир не найден"); + sender.sendMessage(BLUE + "Мир не найден"); return true; } Flag flag = Flags.fuzzyMatchFlag(WorldGuard.getInstance().getFlagRegistry(), args[2]); if (flag == null) { - sender.sendMessage(ChatColor.BLUE + "Флаг не найден"); + sender.sendMessage(BLUE + "Флаг не найден"); return true; } try { @@ -135,9 +128,9 @@ public boolean onCommand(CommandSender sender, Command arg1, String label, Strin } AutoFlags.setFlag(WGRegionUtils.wrapAsPrivileged(sender), world, region, flag, value); } - sender.sendMessage(ChatColor.BLUE + "Флаги установлены"); + sender.sendMessage(BLUE + "Флаги установлены"); } catch (CommandException e) { - sender.sendMessage(ChatColor.BLUE + "Неправильный формат флага " + flag.getName() + ": " + e.getMessage()); + sender.sendMessage(BLUE + "Неправильный формат флага " + flag.getName() + ": " + e.getMessage()); } return true; } @@ -157,7 +150,7 @@ public boolean onCommand(CommandSender sender, Command arg1, String label, Strin region.setMembers(members); } } - sender.sendMessage(ChatColor.BLUE + "Игрок удалён из списков " + (owner ? "владельцев" : "участников") + " всех регионов"); + sender.sendMessage(BLUE + "Игрок удалён из списков " + (owner ? "владельцев" : "участников") + " всех регионов"); return true; } } diff --git a/src/wgextender/features/claimcommand/WGRegionCommandWrapper.java b/src/wgextender/features/claimcommand/WGRegionCommandWrapper.java index 33f6b15..a8270d3 100644 --- a/src/wgextender/features/claimcommand/WGRegionCommandWrapper.java +++ b/src/wgextender/features/claimcommand/WGRegionCommandWrapper.java @@ -18,7 +18,6 @@ package wgextender.features.claimcommand; import com.sk89q.minecraft.util.commands.CommandException; -import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -27,6 +26,9 @@ import wgextender.utils.WEUtils; import wgextender.utils.WGRegionUtils; +import static org.bukkit.ChatColor.RED; +import static org.bukkit.ChatColor.YELLOW; + public class WGRegionCommandWrapper extends Command { public static void inject(Config config) { @@ -57,7 +59,7 @@ public boolean execute(CommandSender sender, String label, String[] args) { if (config.claimExpandSelectionVertical) { boolean result = WEUtils.expandVert((Player) sender); if (result) { - player.sendMessage(ChatColor.YELLOW + "Регион автоматически расширен по вертикали"); + player.sendMessage(YELLOW + "Регион автоматически расширен по вертикали"); } } if (!process(player)) { @@ -70,7 +72,7 @@ public boolean execute(CommandSender sender, String label, String[] args) { AutoFlags.setFlagsForRegion(WGRegionUtils.wrapAsPrivileged(player), player.getWorld(), config, regionName); } } catch (CommandException ex) { - sender.sendMessage(ChatColor.RED + ex.getMessage()); + sender.sendMessage(RED + ex.getMessage()); } return true; } else { @@ -83,23 +85,23 @@ private boolean process(Player player) { switch (info.result()) { default: return true; case DENY_MAX_VOLUME: { - player.sendMessage(ChatColor.RED + "Вы не можете заприватить такой большой регион"); - player.sendMessage(ChatColor.RED + "Ваш лимит: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); + player.sendMessage(RED + "Вы не можете заприватить такой большой регион"); + player.sendMessage(RED + "Ваш лимит: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); return false; } case DENY_MIN_VOLUME: { - player.sendMessage(ChatColor.RED + "Вы не можете заприватить такой маленький регион"); - player.sendMessage(ChatColor.RED + "Минимальный объем: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); + player.sendMessage(RED + "Вы не можете заприватить такой маленький регион"); + player.sendMessage(RED + "Минимальный объем: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); return false; } case DENY_HORIZONTAL: { - player.sendMessage(ChatColor.RED + "Вы не можете заприватить такой маленький регион"); - player.sendMessage(ChatColor.RED + "Минимальная ширина: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); + player.sendMessage(RED + "Вы не можете заприватить такой маленький регион"); + player.sendMessage(RED + "Минимальная ширина: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); return false; } case DENY_VERTICAL: { - player.sendMessage(ChatColor.RED + "Вы не можете заприватить такой низкий регион"); - player.sendMessage(ChatColor.RED + "Минимальная высота: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); + player.sendMessage(RED + "Вы не можете заприватить такой низкий регион"); + player.sendMessage(RED + "Минимальная высота: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize()); return false; } } diff --git a/src/wgextender/features/flags/OldPVPFlagsHandler.java b/src/wgextender/features/flags/OldPVPFlagsHandler.java index ffdba76..aa59e93 100644 --- a/src/wgextender/features/flags/OldPVPFlagsHandler.java +++ b/src/wgextender/features/flags/OldPVPFlagsHandler.java @@ -3,6 +3,7 @@ import com.google.common.base.Function; import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.Server; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; @@ -16,16 +17,12 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.plugin.Plugin; import wgextender.WGExtender; -import wgextender.utils.ReflectionUtils; import wgextender.utils.WGRegionUtils; import java.lang.reflect.Field; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.logging.Level; public class OldPVPFlagsHandler implements Listener { @@ -33,13 +30,25 @@ public class OldPVPFlagsHandler implements Listener { private static final Set PVP_MODIFIERS = EnumSet.of( DamageModifier.ARMOR, DamageModifier.RESISTANCE, DamageModifier.MAGIC, DamageModifier.ABSORPTION ); - protected final Map oldValues = new HashMap<>(); - protected Field functionsField; + private final Map oldValues = new HashMap<>(); + private Field functionsField; - public void start() { - functionsField = ReflectionUtils.getField(EntityDamageEvent.class, "modifierFunctions"); - Bukkit.getPluginManager().registerEvents(this, WGExtender.getInstance()); - Bukkit.getScheduler().runTaskTimer(WGExtender.getInstance(), () -> { + public void start(Plugin plugin) { + try { + functionsField = EntityDamageEvent.class.getDeclaredField("modifierFunctions"); + functionsField.setAccessible(true); + } catch (Exception ex) { + plugin.getLogger().log( + Level.SEVERE, + "Couldn't get access to 'modifierFunctions' field. Old PvP flags will not be enabled", + ex + ); + return; + } + + Server server = plugin.getServer(); + server.getPluginManager().registerEvents(this, plugin); + server.getScheduler().runTaskTimer(WGExtender.getInstance(), () -> { for (Player player : Bukkit.getOnlinePlayers()) { if (WGRegionUtils.isFlagTrue(player.getLocation(), WGExtenderFlags.OLDPVP_ATTACKSPEED)) { if (!oldValues.containsKey(player.getUniqueId())) { @@ -60,11 +69,6 @@ public void stop() { } } - @EventHandler(priority = EventPriority.LOWEST) - public void onQuit(PlayerQuitEvent event) { - reset(event.getPlayer()); - } - private void reset(Player player) { Double oldValue = oldValues.remove(player.getUniqueId()); if (oldValue != null) { @@ -72,6 +76,11 @@ private void reset(Player player) { } } + @EventHandler(priority = EventPriority.LOWEST) + public void onQuit(PlayerQuitEvent event) { + reset(event.getPlayer()); + } + @SuppressWarnings({"unchecked", "deprecation"}) @EventHandler(priority = EventPriority.LOWEST) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { @@ -109,5 +118,4 @@ public void onInteract(PlayerInteractEvent event) { event.setCancelled(true); } } - } diff --git a/src/wgextender/features/flags/WGExtenderFlags.java b/src/wgextender/features/flags/WGExtenderFlags.java index 2538dc0..db74e79 100644 --- a/src/wgextender/features/flags/WGExtenderFlags.java +++ b/src/wgextender/features/flags/WGExtenderFlags.java @@ -4,16 +4,13 @@ import com.sk89q.worldguard.protection.flags.BooleanFlag; import com.sk89q.worldguard.protection.flags.Flag; import com.sk89q.worldguard.protection.flags.StateFlag; +import com.sk89q.worldguard.protection.flags.registry.FlagConflictException; import com.sk89q.worldguard.protection.flags.registry.FlagRegistry; -import com.sk89q.worldguard.protection.flags.registry.UnknownFlag; -import com.sk89q.worldguard.protection.managers.RegionManager; -import com.sk89q.worldguard.protection.regions.ProtectedRegion; -import wgextender.utils.ReflectionUtils; -import wgextender.utils.WGRegionUtils; import java.util.ArrayList; import java.util.List; -import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; public final class WGExtenderFlags { private WGExtenderFlags() {} @@ -30,44 +27,13 @@ private static > F cache(F flag) { return flag; } - @SuppressWarnings("unchecked") - public static void registerFlags() throws IllegalAccessException { - FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); - Map> flagMap = (Map>) ReflectionUtils.getField(registry.getClass(), "flags").get(registry); - for (var flag : FLAGS) registerFlag(flag, flagMap); - } - - @SuppressWarnings("unchecked") - private static void registerFlag(Flag flag, Map> flagMap) { - //manually insert flag into the registry - Flag prevFlag = flagMap.put(flag.getName().toLowerCase(), flag); - if (prevFlag == null) return; - //change flag instance in every loaded region if had old one - for (RegionManager rm : WGRegionUtils.getRegionContainer().getLoaded()) { - for (ProtectedRegion region : rm.getRegions().values()) { - Map, Object> regionFlags = region.getFlags(); - Object prevValue = regionFlags.remove(prevFlag); - if (prevValue == null) continue; - - //unknown flag will store marshaled value as value directly, so we can try to unmarshal it - if (prevFlag instanceof UnknownFlag) { - try { - Object unmarshalled = flag.unmarshal(prevValue); - if (unmarshalled != null) { - regionFlags.put(flag, unmarshalled); - } - } catch (Throwable ignored) { - } - } - //before reload instance probably, try to marshal value first to see if it is compatible - else { - try { - ((Flag) flag).marshal(prevValue); - regionFlags.put(flag, prevValue); - } catch (Throwable ignored) { - } - } - region.setDirty(true); + public static void registerFlags(Logger log) { + FlagRegistry flagRegistry = WorldGuard.getInstance().getFlagRegistry(); + for (var flag : FLAGS) { + try { + flagRegistry.register(flag); + } catch (FlagConflictException ex) { + log.log(Level.SEVERE, "Unable to register '" + flag.getName() + "' flag - already registered", ex); } } } diff --git a/src/wgextender/features/regionprotect/WGOverrideListener.java b/src/wgextender/features/regionprotect/WGOverrideListener.java index d95d186..79e7525 100644 --- a/src/wgextender/features/regionprotect/WGOverrideListener.java +++ b/src/wgextender/features/regionprotect/WGOverrideListener.java @@ -11,7 +11,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; public abstract class WGOverrideListener implements Listener { @@ -23,7 +22,7 @@ public void inject() throws IllegalAccessException, InvocationTargetException, N if (method.isAnnotationPresent(EventHandler.class)) { Class eventClass = method.getParameterTypes()[0]; HandlerList hl = (HandlerList) eventClass.getMethod("getHandlerList").invoke(null); - for (RegisteredListener listener : new ArrayList<>(Arrays.asList(hl.getRegisteredListeners()))) { + for (RegisteredListener listener : hl.getRegisteredListeners()) { if (listener.getListener().getClass() == getClassToReplace()) { overriddenEvents.add(Pair.of(hl, listener)); hl.unregister(listener); diff --git a/src/wgextender/features/regionprotect/ownormembased/PvPHandlingListener.java b/src/wgextender/features/regionprotect/ownormembased/PvPHandlingListener.java index f1f0fe3..abd2331 100644 --- a/src/wgextender/features/regionprotect/ownormembased/PvPHandlingListener.java +++ b/src/wgextender/features/regionprotect/ownormembased/PvPHandlingListener.java @@ -39,7 +39,10 @@ public class PvPHandlingListener extends WGOverrideListener { - protected final Config config; + private final Config config; + + private static final String DENY_MESSAGE_KEY = "worldguard.region.lastMessage"; + private static final int LAST_MESSAGE_DELAY = 500; public PvPHandlingListener(Config config) { this.config = config; @@ -153,26 +156,25 @@ public void onDamageEntity(DamageEntityEvent event) { } private RegionAssociable createRegionAssociable(Cause cause) { - Object rootCause = cause.getRootCause(); - if (!cause.isKnown()) { return Associables.constant(Association.NON_MEMBER); - } else if (rootCause instanceof Player player) { - return WorldGuardPlugin.inst().wrapPlayer(player); - } else if (rootCause instanceof OfflinePlayer offlinePlayer) { - return WorldGuardPlugin.inst().wrapOfflinePlayer(offlinePlayer); - } else if (rootCause instanceof Entity entity) { - return new DelayedRegionOverlapAssociation(WGRegionUtils.REGION_QUERY, BukkitAdapter.adapt(entity.getLocation())); - } else if (rootCause instanceof Block block) { - return new DelayedRegionOverlapAssociation(WGRegionUtils.REGION_QUERY, BukkitAdapter.adapt(block.getLocation())); - } else { - return Associables.constant(Association.NON_MEMBER); } + + return switch (cause.getRootCause()) { + case Player player -> WorldGuardPlugin.inst().wrapPlayer(player); + case OfflinePlayer offlinePlayer -> WorldGuardPlugin.inst().wrapOfflinePlayer(offlinePlayer); + case Entity entity -> new DelayedRegionOverlapAssociation( + WGRegionUtils.REGION_QUERY, BukkitAdapter.adapt(entity.getLocation()) + ); + case Block block -> new DelayedRegionOverlapAssociation( + WGRegionUtils.REGION_QUERY, BukkitAdapter.adapt(block.getLocation()) + ); + case null, default -> Associables.constant(Association.NON_MEMBER); + }; } private boolean isWhitelisted(Cause cause, World world, boolean pvp) { Object rootCause = cause.getRootCause(); - if (rootCause instanceof Block block) { Material type = block.getType(); return (type == Material.HOPPER) || (type == Material.DROPPER); @@ -186,17 +188,12 @@ private boolean isWhitelisted(Cause cause, World world, boolean pvp) { } } - private static final String DENY_MESSAGE_KEY = "worldguard.region.lastMessage"; - private static final int LAST_MESSAGE_DELAY = 500; - private void tellErrorMessage(DelegateEvent event, Cause cause, Location location, String what) { if (event.isSilent() || cause.isIndirect()) { return; } - Object rootCause = cause.getRootCause(); - - if (rootCause instanceof Player player) { + if (cause.getRootCause() instanceof Player player) { long now = System.currentTimeMillis(); Long lastTime = WGMetadata.getIfPresent(player, DENY_MESSAGE_KEY, Long.class); if ((lastTime == null) || ((now - lastTime) >= LAST_MESSAGE_DELAY)) { @@ -218,5 +215,4 @@ private static StateFlag[] combine(DelegateEvent event, StateFlag... flag) { } return flags; } - } diff --git a/src/wgextender/utils/ReflectionUtils.java b/src/wgextender/utils/ReflectionUtils.java deleted file mode 100644 index 1ffc3f9..0000000 --- a/src/wgextender/utils/ReflectionUtils.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 3 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -package wgextender.utils; - -import java.lang.reflect.Field; - -public class ReflectionUtils { - - public static Field getField(Class clazz, String name) { - do { - for (Field field : clazz.getDeclaredFields()) { - if (field.getName().equals(name)) { - field.setAccessible(true); - return field; - } - } - } while ((clazz = clazz.getSuperclass()) != null); - throw new RuntimeException("Can't find field " + name); - } - -}