TotalFreedomMod/src/me/totalfreedom/totalfreedommod/commands/Command_debug.java

113 lines
3.7 KiB
Java
Raw Normal View History

package me.totalfreedom.totalfreedommod.commands;
2013-07-28 21:31:41 +00:00
import me.totalfreedom.totalfreedommod.permission.PlayerRank;
2013-07-28 21:31:41 +00:00
import java.lang.reflect.Field;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
2013-07-28 21:31:41 +00:00
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = PlayerRank.SENIOR_ADMIN, source = SourceType.ONLY_CONSOLE)
2013-07-28 21:31:41 +00:00
@CommandParameters(description = "For developers only - debug things via reflection.", usage = "/<command>")
public class Command_debug extends FreedomCommand
2013-07-28 21:31:41 +00:00
{
@Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length < 3)
{
return false;
}
try
{
String className = args[0];
String fieldName = args[1];
String newValue = StringUtils.join(ArrayUtils.subarray(args, 2, args.length), " ");
if (className.equalsIgnoreCase("_"))
{
className = "me.StevenLawson.TotalFreedomMod.TotalFreedomMod";
}
setStaticValue(className, fieldName, newValue);
sender.sendMessage("Debug: OK");
}
catch (Exception ex)
{
sender.sendMessage(ex.getMessage());
}
2013-07-28 21:31:41 +00:00
return true;
}
public static void setStaticValue(final String className, final String fieldName, final String newValueString) throws Exception
2013-07-28 21:31:41 +00:00
{
Class<?> forName = Class.forName(className);
if (forName != null)
2013-07-28 21:31:41 +00:00
{
final Field field = forName.getDeclaredField(fieldName);
if (field != null)
2013-07-28 21:31:41 +00:00
{
Object newValue;
2013-07-28 21:31:41 +00:00
Class<?> type = field.getType();
if (type.isPrimitive())
{
if (type.getName().equals("int"))
{
newValue = Integer.parseInt(newValueString);
}
else if (type.getName().equals("double"))
{
newValue = Double.parseDouble(newValueString);
}
else if (type.getName().equals("boolean"))
{
newValue = Boolean.parseBoolean(newValueString);
}
else
{
throw new Exception("Unknown primitive field type.");
}
}
else
{
if (type.isAssignableFrom(Integer.class))
{
newValue = new Integer(newValueString);
}
else if (type.isAssignableFrom(Double.class))
{
newValue = new Double(newValueString);
}
else if (type.isAssignableFrom(Boolean.class))
{
newValue = Boolean.valueOf(newValueString);
}
else if (type.isAssignableFrom(String.class))
{
newValue = newValueString;
}
else
{
throw new Exception("Unknown complex field type.");
}
}
2013-07-28 21:31:41 +00:00
field.setAccessible(true);
2013-07-28 21:31:41 +00:00
final Object oldValue = field.get(Class.forName(className));
if (oldValue != null)
{
field.set(oldValue, newValue);
2013-07-28 21:31:41 +00:00
}
field.setAccessible(false);
2013-07-28 21:31:41 +00:00
}
}
}
}