1
0
mirror of https://e.coding.net/circlecloud/YumCore.git synced 2024-11-21 01:38:51 +00:00

feat: 兼容新的刷怪蛋 调整一些小问题

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2019-09-30 17:44:16 +08:00
parent 558157da8a
commit 857a903336
4 changed files with 609 additions and 590 deletions

View File

@ -1,184 +1,185 @@
package pw.yumc.YumCore.bukkit; package pw.yumc.YumCore.bukkit;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Arrays; import java.util.Arrays;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
/** /**
* 插件Instance获取类 * 插件Instance获取类
* *
* @author * @author
* @since 2016年7月23日 上午9:09:57 * @since 2016年7月23日 上午9:09:57
*/ */
public class P { public class P {
/** /**
* 插件实例 * 插件实例
*/ */
public static JavaPlugin instance; public static JavaPlugin instance;
/** /**
* 插件配置方法 * 插件配置方法
*/ */
public static Method getInjectConfigMethod; public static Method getInjectConfigMethod;
static { static {
Object pluginClassLoader = P.class.getClassLoader(); Object pluginClassLoader = P.class.getClassLoader();
try { try {
Field field = pluginClassLoader.getClass().getDeclaredField("plugin"); Field field = pluginClassLoader.getClass().getDeclaredField("plugin");
field.setAccessible(true); field.setAccessible(true);
instance = (JavaPlugin) field.get(pluginClassLoader); instance = (JavaPlugin) field.get(pluginClassLoader);
try { try {
getInjectConfigMethod = instance.getClass().getMethod("get" + instance.getName() + "Config"); getInjectConfigMethod = instance.getClass().getMethod("get" + instance.getName() + "Config");
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
Log.d("配置方法 get%sConfig 未找到 将返回getConfig 调用结果!", instance.getName()); Log.d("配置方法 get%sConfig 未找到 将返回getConfig 调用结果!", instance.getName());
} }
} catch (Exception e) { } catch (Exception e) {
Log.d("P 类初始化失败 %s:%s", e.getClass().getName(), e.getMessage()); Log.d("P 类初始化失败 %s:%s", e.getClass().getName(), e.getMessage());
} Log.d(e);
} }
}
/**
* @param name /**
* 命令名称 * @param name
* @return 插件命令 * 命令名称
*/ * @return 插件命令
public static PluginCommand getCommand(String name) { */
return instance.getCommand(name); public static PluginCommand getCommand(String name) {
} return instance.getCommand(name);
}
/**
* @param <FC> /**
* 配置源类型 * @param <FC>
* @return 获得插件配置文件 * 配置源类型
*/ * @return 获得插件配置文件
public static <FC> FC getConfig() { */
return (FC) instance.getConfig(); public static <FC> FC getConfig() {
} return (FC) instance.getConfig();
}
/**
* @param <FC> /**
* 注入配置源类型 * @param <FC>
* @return 获得插件注入配置 * 注入配置源类型
*/ * @return 获得插件注入配置
public static <FC> FC getInjectConfig() { */
try { public static <FC> FC getInjectConfig() {
return (FC) getInjectConfigMethod.invoke(instance); try {
} catch (IllegalAccessException | InvocationTargetException ignored) { return (FC) getInjectConfigMethod.invoke(instance);
} } catch (IllegalAccessException | InvocationTargetException ignored) {
return getConfig(); }
} return getConfig();
}
/**
* @return 获得插件文件夹 /**
*/ * @return 获得插件文件夹
public static File getDataFolder() { */
return instance.getDataFolder(); public static File getDataFolder() {
} return instance.getDataFolder();
}
/**
* @return 获得插件描述文件 /**
*/ * @return 获得插件描述文件
public static PluginDescriptionFile getDescription() { */
return instance.getDescription(); public static PluginDescriptionFile getDescription() {
} return instance.getDescription();
}
/**
* @return 获得插件日志器 /**
*/ * @return 获得插件日志器
public static Logger getLogger() { */
return instance.getLogger(); public static Logger getLogger() {
} return instance.getLogger();
}
/**
* @return 插件名称 /**
*/ * @return 插件名称
public static String getName() { */
return instance.getName(); public static String getName() {
} return instance.getName();
}
/**
* @param <PI> /**
* 插件源类型 * @param <PI>
* @return 获得插件 * 插件源类型
*/ * @return 获得插件
public static <PI> PI getPlugin() { */
return (PI) instance; public static <PI> PI getPlugin() {
} return (PI) instance;
}
/**
* @return 插件是否已启用 /**
*/ * @return 插件是否已启用
public static boolean isEnabled() { */
return instance.isEnabled(); public static boolean isEnabled() {
} return instance.isEnabled();
}
/**
* 批量注册监听器 /**
* * 批量注册监听器
* @param listeners *
* 监听器 * @param listeners
*/ * 监听器
public static void registerEvents(Listener... listeners) { */
Arrays.stream(listeners).forEach(listener -> Bukkit.getPluginManager().registerEvents(listener, instance)); public static void registerEvents(Listener... listeners) {
} Arrays.stream(listeners).forEach(listener -> Bukkit.getPluginManager().registerEvents(listener, instance));
}
/**
* 保存文件 /**
* * 保存文件
* @param dirs *
* 目录 * @param dirs
*/ * 目录
public static void saveFile(final String... dirs) { */
saveFile(false, dirs); public static void saveFile(final String... dirs) {
} saveFile(false, dirs);
}
/**
* 保存文件 /**
* * 保存文件
* @param replace *
* 是否替换 * @param replace
* @param dirs * 是否替换
* 目录 * @param dirs
*/ * 目录
public static void saveFile(boolean replace, final String... dirs) { */
URL url = instance.getClass().getClassLoader().getResource("plugin.yml"); public static void saveFile(boolean replace, final String... dirs) {
if (url == null) { return; } URL url = instance.getClass().getClassLoader().getResource("plugin.yml");
String upath = url.getFile().substring(url.getFile().indexOf("/") + 1); if (url == null) { return; }
String jarPath = URLDecoder.decode(upath.substring(0, upath.indexOf('!'))); String upath = url.getFile().substring(url.getFile().indexOf("/") + 1);
if (!new File(jarPath).exists()) { String jarPath = URLDecoder.decode(upath.substring(0, upath.indexOf('!')));
jarPath = "/" + jarPath; if (!new File(jarPath).exists()) {
} jarPath = "/" + jarPath;
try (JarFile jar = new JarFile(jarPath)) { }
jar.stream().forEach(je -> { try (JarFile jar = new JarFile(jarPath)) {
if (!je.isDirectory()) { jar.stream().forEach(je -> {
for (final String dir : dirs) { if (!je.isDirectory()) {
if (je.getName().startsWith(dir)) { for (final String dir : dirs) {
if (!replace) { if (je.getName().startsWith(dir)) {
// 不替换 并且文件不存在 if (!replace) {
if (!new File(getDataFolder(), je.getName()).exists()) { // 不替换 并且文件不存在
instance.saveResource(je.getName(), false); if (!new File(getDataFolder(), je.getName()).exists()) {
} instance.saveResource(je.getName(), false);
} else { }
instance.saveResource(je.getName(), true); } else {
} instance.saveResource(je.getName(), true);
} }
} }
} }
}); }
} catch (IOException e) { });
Log.d(e); } catch (IOException e) {
} Log.d(e);
} }
} }
}

View File

@ -1,265 +1,274 @@
package pw.yumc.YumCore.commands; package pw.yumc.YumCore.commands;
import java.io.File; import java.io.File;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import pw.yumc.YumCore.bukkit.Log; import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.commands.annotation.Option; import pw.yumc.YumCore.commands.annotation.Option;
import pw.yumc.YumCore.commands.exception.ParseException; import pw.yumc.YumCore.commands.exception.ParseException;
/** /**
* 命令参数解析 * 命令参数解析
* *
* @author * @author
* @since 2016年10月5日 下午4:02:04 * @since 2016年10月5日 下午4:02:04
*/ */
public class CommandParse { public class CommandParse {
private static Map<Class, Class> allparses = new HashMap<>(); private static Map<Class, Class> allparses = new HashMap<>();
private static Map<String, Class> primitiveMap = new HashMap<>(); private static Map<String, Class> primitiveMap = new HashMap<>();
private boolean isMain; private boolean isMain;
private List<Parse> parses = new LinkedList<>(); private List<Parse> parses = new LinkedList<>();
static { static {
register(File.class, FileParse.class); register(File.class, FileParse.class);
register(Player.class, PlayerParse.class); register(Player.class, PlayerParse.class);
register(String.class, StringParse.class); register(String.class, StringParse.class);
primitiveMap.put("boolean", Boolean.class); primitiveMap.put("boolean", Boolean.class);
primitiveMap.put("byte", Byte.class); primitiveMap.put("byte", Byte.class);
primitiveMap.put("char", Character.class); primitiveMap.put("char", Character.class);
primitiveMap.put("short", Short.class); primitiveMap.put("short", Short.class);
primitiveMap.put("int", Integer.class); primitiveMap.put("int", Integer.class);
primitiveMap.put("long", Long.class); primitiveMap.put("long", Long.class);
primitiveMap.put("float", Float.class); primitiveMap.put("float", Float.class);
primitiveMap.put("double", Double.class); primitiveMap.put("double", Double.class);
} }
public CommandParse(Class[] classes, Annotation[][] annons, boolean isMain) { public CommandParse(Class[] classes, Annotation[][] annons, boolean isMain) {
this.isMain = isMain; this.isMain = isMain;
// 第一个参数实现了CommandSender忽略 // 第一个参数实现了CommandSender忽略
for (int i = 1; i < classes.length; i++) { for (int i = 1; i < classes.length; i++) {
Class clazz = classes[i]; Class clazz = classes[i];
if (clazz.isPrimitive()) { if (clazz.isPrimitive()) {
// boolean, byte, char, short, int, long, float, and double. // boolean, byte, char, short, int, long, float, and double.
clazz = primitiveMap.get(clazz.getName()); clazz = primitiveMap.get(clazz.getName());
} }
Annotation[] annotations = annons[i]; Annotation[] annotations = annons[i];
Parse parse = null; Parse parse = null;
if (allparses.containsKey(clazz)) { if (allparses.containsKey(clazz)) {
try { try {
parse = (Parse) allparses.get(clazz).newInstance(); parse = (Parse) allparses.get(clazz).newInstance();
} catch (InstantiationException | IllegalAccessException | NullPointerException ignored) { } catch (InstantiationException | IllegalAccessException | NullPointerException ignored) {
} }
} else { } else {
try { try {
parse = new ValueOfParse(clazz, clazz.getDeclaredMethod("valueOf", String.class)); parse = new ValueOfParse(clazz, clazz.getDeclaredMethod("valueOf", String.class));
} catch (NoSuchMethodException ignored) { } catch (NoSuchMethodException ignored) {
} }
} }
if (parse == null) { throw new ParseException(String.format("存在无法解析的参数类型 %s", clazz.getName())); } if (parse == null) { throw new ParseException(String.format("存在无法解析的参数类型 %s", clazz.getName())); }
this.parses.add(parse.parseAnnotation(annotations).handleAttrs()); this.parses.add(parse.parseAnnotation(annotations).handleAttrs());
} }
Log.d("命令解析器 %s", Log.getSimpleNames(parses.toArray())); Log.d("命令解析器 %s", Log.getSimpleNames(parses.toArray()));
} }
public static CommandParse get(Method method) { public static CommandParse get(Method method) {
return new CommandParse(method.getParameterTypes(), method.getParameterAnnotations(), method.getReturnType().equals(boolean.class)); return new CommandParse(method.getParameterTypes(), method.getParameterAnnotations(), method.getReturnType().equals(boolean.class));
} }
/** /**
* 转化数组为字符串 * 转化数组为字符串
* *
* @param arr * @param arr
* 数组 * 数组
* @param split * @param split
* 分割符 * 分割符
* @return 字符串 * @return 字符串
*/ */
public static String join(Object[] arr, String split) { public static String join(Object[] arr, String split) {
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
for (Object s : arr) { for (Object s : arr) {
str.append(s.toString()); str.append(s.toString());
str.append(split); str.append(split);
} }
return str.length() > split.length() ? str.toString().substring(0, str.length() - split.length()) : str.toString(); return str.length() > split.length() ? str.toString().substring(0, str.length() - split.length()) : str.toString();
} }
public static void register(Class clazz, Class parse) { public static void register(Class clazz, Class parse) {
allparses.put(clazz, parse); allparses.put(clazz, parse);
} }
public Object[] parse(CommandSender sender, String label, String[] args) { public Object[] parse(CommandSender sender, String label, String[] args) {
List<Object> pobjs = new LinkedList<>(); List<Object> pobjs = new LinkedList<>();
pobjs.add(sender); pobjs.add(sender);
for (int i = 0; i < parses.size(); i++) { for (int i = 0; i < parses.size(); i++) {
try { try {
Parse p = parses.get(i); Parse p = parses.get(i);
String param = i < args.length ? args[i] : p.getDefault(); String param = i < args.length ? args[i] : null;
// 参数大于解析器 并且为最后一个参数 param = param == null ? p.getDefault(sender) : param;
if (i + 1 == parses.size() && args.length >= parses.size()) { // 参数大于解析器 并且为最后一个参数
param = join(Arrays.copyOfRange(args, i, args.length), " "); if (i + 1 == parses.size() && args.length >= parses.size()) {
} param = join(Arrays.copyOfRange(args, i, args.length), " ");
pobjs.add(param == null ? null : p.parse(sender, param)); }
} catch (Exception e) { // 尝试让解析器解析Null参数
Log.fd(e); try { pobjs.add(p.parse(sender, param)); } catch (NullPointerException npe) { pobjs.add(null); }
throw new ParseException(String.format("第 %s 个参数 %s", isMain ? 1 : 2 + i, e.getMessage())); } catch (Exception e) {
} Log.fd(e);
} throw new ParseException(String.format("第 %s 个参数 %s", isMain ? 1 : 2 + i, e.getMessage()));
Log.d("解析参数: %s => %s", Arrays.toString(args), Log.getSimpleNames(pobjs.toArray())); }
return pobjs.toArray(); }
} Log.d("解析参数: %s => %s", Arrays.toString(args), Log.getSimpleNames(pobjs.toArray()));
return pobjs.toArray();
public static abstract class Parse<RT> { }
protected Map<String, String> attrs = new HashMap<>();
protected String def; public static abstract class Parse<RT> {
protected int max = Integer.MAX_VALUE; protected Map<String, String> attrs = new HashMap<>();
protected int min = 0; protected String def;
protected int max = Integer.MAX_VALUE;
public String getDefault() { protected int min = 0;
return def;
} public String getDefault(CommandSender sender) {
return def;
public abstract RT parse(CommandSender sender, String arg) throws ParseException; }
public Parse<RT> parseAnnotation(Annotation[] annotations) { public abstract RT parse(CommandSender sender, String arg) throws ParseException;
for (Annotation annotation : annotations) {
if (annotation.annotationType() == Option.class) { public Parse<RT> parseAnnotation(Annotation[] annotations) {
String value = ((Option) annotation).value(); for (Annotation annotation : annotations) {
for (String str : value.split(" ")) { if (annotation.annotationType() == Option.class) {
if (str.isEmpty()) { String value = ((Option) annotation).value();
continue; for (String str : value.split(" ")) {
} if (str.isEmpty()) {
if (str.contains(":")) { continue;
String[] args = str.split(":"); }
attrs.put(args[0], args[1]); if (str.contains(":")) {
} else { String[] args = str.split(":");
attrs.put(str, null); attrs.put(args[0], args[1]);
} } else {
} attrs.put(str, null);
} }
} }
return this; }
} }
return this;
public Parse<RT> handleAttrs() { }
if (attrs.containsKey("def")) {
def = String.valueOf(attrs.get("def")); public Parse<RT> handleAttrs() {
} if (attrs.containsKey("def")) {
if (attrs.containsKey("min")) { def = String.valueOf(attrs.get("def"));
min = Integer.parseInt(String.valueOf(attrs.get("min"))); }
} if (attrs.containsKey("min")) {
if (attrs.containsKey("max")) { min = Integer.parseInt(String.valueOf(attrs.get("min")));
max = Integer.parseInt(String.valueOf(attrs.get("max"))); }
} if (attrs.containsKey("max")) {
return this; max = Integer.parseInt(String.valueOf(attrs.get("max")));
} }
return this;
public <T> T throwException(String str, Object... objects) { }
throw new ParseException(String.format(str, objects));
} public <T> T throwException(String str, Object... objects) {
throw new ParseException(String.format(str, objects));
public void throwRange() { }
throwRange("");
} public void throwRange() {
throwRange("");
public <T> T throwRange(String str) { }
return throwException(str.isEmpty() ? "范围必须在 %s 到 %s 之间!" : str, min, max);
} public <T> T throwRange(String str) {
} return throwException(str.isEmpty() ? "范围必须在 %s 到 %s 之间!" : str, min, max);
}
public static class ValueOfParse extends Parse<Object> { }
private Class etype;
private Enum[] elist; public static class ValueOfParse extends Parse<Object> {
private Method method; private Class eType;
private Method checker; private Enum[] eList;
private Method method;
public ValueOfParse(Class etype, Method method) { private Method checker;
this.etype = etype;
try { public ValueOfParse(Class eType, Method method) {
checker = etype.getDeclaredMethod("doubleValue"); this.eType = eType;
} catch (NoSuchMethodException ignored) { try {
} checker = eType.getDeclaredMethod("doubleValue");
this.method = method; } catch (NoSuchMethodException ignored) {
if (etype.isEnum()) { }
this.elist = ((Class<Enum>) etype).getEnumConstants(); this.method = method;
} if (eType.isEnum()) {
} this.eList = ((Class<Enum>) eType).getEnumConstants();
}
@Override }
public Object parse(CommandSender sender, String arg) {
try { @Override
Object result = method.invoke(null, arg); public Object parse(CommandSender sender, String arg) {
if (checker != null) { try {
double num = (double) checker.invoke(result); Object result = method.invoke(null, arg);
if (min > num || num > max) { if (checker != null) {
throwRange(); double num = (double) checker.invoke(result);
} if (min > num || num > max) {
} throwRange();
return result; }
} catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) { }
if (etype.isEnum() && elist.length < 21) { return result;
return throwException("%s 不是 %s 有效值为 %s", arg, etype.getSimpleName(), Arrays.toString(elist)); } catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) {
} else { if (eType.isEnum() && eList.length < 21) {
return throwException("%s 不是一个有效的 %s", arg, etype.getSimpleName()); return throwException("%s 不是 %s 有效值为 %s", arg, eType.getSimpleName(), Arrays.toString(eList));
} } else {
} return throwException("%s 不是一个有效的 %s", arg, eType.getSimpleName());
} }
} }
}
public static class FileParse extends Parse<File> { }
@Override
public File parse(CommandSender sender, String arg) throws ParseException { public static class FileParse extends Parse<File> {
File file = new File(arg); @Override
if (attrs.containsKey("check") && !file.exists()) { throw new ParseException("文件 " + arg + " 不存在!"); } public File parse(CommandSender sender, String arg) throws ParseException {
return file; File file = new File(arg);
} if (attrs.containsKey("check") && !file.exists()) { throw new ParseException("文件 " + arg + " 不存在!"); }
} return file;
}
public static class PlayerParse extends Parse<Player> { }
boolean check = false;
public static class PlayerParse extends Parse<Player> {
@Override boolean sender = false;
public Player parse(CommandSender sender, String arg) { boolean check = false;
Player p = Bukkit.getPlayerExact(arg);
if (check && p == null) { return throwException("玩家 %s 不存在或不在线!", arg); } @Override
return p; public Player parse(CommandSender sender, String arg) {
} Player p = Bukkit.getPlayerExact(arg);
if (this.check && p == null) { return throwException("玩家 %s 不存在或不在线!", arg); }
@Override return p;
public Parse<Player> handleAttrs() { }
super.handleAttrs();
check = attrs.containsKey("check"); @Override
return this; public Parse<Player> handleAttrs() {
} super.handleAttrs();
} sender = attrs.containsKey("sender");
check = attrs.containsKey("check");
public static class StringParse extends Parse<String> { return this;
List<String> options; }
@Override @Override
public String parse(CommandSender sender, String arg) { public String getDefault(CommandSender sender) {
if (min > arg.length() || arg.length() > max) { return throwRange("长度必须在 %s 和 %s 之间!"); } return this.sender && sender instanceof Player ? sender.getName() : super.getDefault(sender);
if (options != null && !options.contains(arg)) { return throwException("参数 %s 不是一个有效的选项 有效值为 %s", arg, options); } }
return arg; }
}
public static class StringParse extends Parse<String> {
@Override List<String> options;
public Parse<String> handleAttrs() {
super.handleAttrs(); @Override
if (attrs.containsKey("option")) { public String parse(CommandSender sender, String arg) {
options = Arrays.asList(attrs.get("option").split(",")); if (min > arg.length() || arg.length() > max) { return throwRange("长度必须在 %s 和 %s 之间!"); }
} if (options != null && !options.contains(arg)) { return throwException("参数 %s 不是一个有效的选项 有效值为 %s", arg, options); }
return this; return arg;
} }
}
} @Override
public Parse<String> handleAttrs() {
super.handleAttrs();
if (attrs.containsKey("option")) {
options = Arrays.asList(attrs.get("option").split(","));
}
return this;
}
}
}

View File

@ -70,6 +70,9 @@ public class CommandSub implements TabExecutor {
*/ */
private List<String> cmdNameCache = new ArrayList<>(); private List<String> cmdNameCache = new ArrayList<>();
public CommandSub() {
}
/** /**
* 命令管理器 * 命令管理器
* *
@ -178,9 +181,9 @@ public class CommandSub implements TabExecutor {
if (defCmd != null) { return defCmd.execute(sender, label, args); } if (defCmd != null) { return defCmd.execute(sender, label, args); }
return help.send(sender, label, args); return help.send(sender, label, args);
} }
String subcmd = args[0].toLowerCase(); String subCmd = args[0].toLowerCase();
if (subcmd.equalsIgnoreCase("help")) { return help.send(sender, label, args); } if ("help".equalsIgnoreCase(subCmd)) { return help.send(sender, label, args); }
CommandInfo cmd = getByCache(subcmd); CommandInfo cmd = getByCache(subCmd);
String[] subargs = args; String[] subargs = args;
if (cmd.equals(CommandInfo.Unknow) && defCmd != null) { if (cmd.equals(CommandInfo.Unknow) && defCmd != null) {
cmd = defCmd; cmd = defCmd;
@ -238,7 +241,7 @@ public class CommandSub implements TabExecutor {
CommandInfo ci = CommandInfo.parse(method, clazz); CommandInfo ci = CommandInfo.parse(method, clazz);
if (ci != null) { if (ci != null) {
Class[] params = method.getParameterTypes(); Class[] params = method.getParameterTypes();
Log.d("注册子命令: %s 参数类型: %s", ci.getName(), Log.getSimpleNames((Object[]) params)); Log.d("注册子命令: %s 参数类型: %s", ci.getName(), Log.getSimpleNames(params));
try { try {
Class<? extends CommandSender> sender = params[0]; Class<? extends CommandSender> sender = params[0];
// 用于消除unuse警告 // 用于消除unuse警告

View File

@ -1,137 +1,143 @@
package pw.yumc.YumCore.global; package pw.yumc.YumCore.global;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.material.SpawnEgg; import org.bukkit.inventory.meta.SpawnEggMeta;
import org.bukkit.material.SpawnEgg;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.config.FileConfig; import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.config.ext.YumConfig; import pw.yumc.YumCore.config.FileConfig;
import pw.yumc.YumCore.config.ext.YumConfig;
/**
* 本地化工具类 /**
* * 本地化工具类
* @since 2015年12月14日 下午1:33:52 *
* @author * @author
*/ * @since 2015年12月14日 下午1:33:52
public class L10N { */
private static String CONFIG_NAME = "Item_zh_CN.yml"; public class L10N {
private static FileConfig custom; private static String CONFIG_NAME = "Item_zh_CN.yml";
private static Map<String, String> content; private static FileConfig custom;
private static Map<String, String> content;
static {
content = new HashMap<>(); static {
Log.i("异步初始化本地化工具..."); content = new HashMap<>();
load(); Log.i("异步初始化本地化工具...");
} load();
}
private L10N() {
} private L10N() {
}
/**
* 获取物品完整汉化名称(包括原版) /**
* * 获取物品完整汉化名称(包括原版)
* @param i *
* 物品实体 * @param i
* @return 物品名称 * 物品实体
*/ * @return 物品名称
public static String getFullName(ItemStack i) { */
return getItemName(getItemType(i)) + (i.hasItemMeta() && i.getItemMeta().hasDisplayName() ? "§r(" + i.getItemMeta().getDisplayName() + "§r)" : ""); public static String getFullName(ItemStack i) {
} return getItemName(getItemType(i)) + (i.hasItemMeta() && i.getItemMeta().hasDisplayName() ? "§r(" + i.getItemMeta()
.getDisplayName() + "§r)" : "");
/** }
* 获取物品汉化名称
* /**
* @param i * 获取物品汉化名称
* 物品实体 *
* @return 物品名称 * @param i
*/ * 物品实体
public static String getItemName(ItemStack i) { * @return 物品名称
return getItemName(getItemType(i)); */
} public static String getItemName(ItemStack i) {
return getItemName(getItemType(i));
/** }
* 获取物品汉化名称(优先显示名称)
* /**
* @param i * 获取物品汉化名称(优先显示名称)
* 物品实体 *
* @return 物品名称 * @param i
*/ * 物品实体
public static String getName(ItemStack i) { * @return 物品名称
return i.hasItemMeta() && i.getItemMeta().hasDisplayName() ? i.getItemMeta().getDisplayName() : getItemName(getItemType(i)); */
} public static String getName(ItemStack i) {
return i.hasItemMeta() && i.getItemMeta().hasDisplayName() ? i.getItemMeta().getDisplayName() : getItemName(getItemType(i));
/** }
* 重载LocalUtil
*/ /**
public static void reload() { * 重载LocalUtil
Log.i("异步重载本地化工具..."); */
content.clear(); public static void reload() {
load(); Log.i("异步重载本地化工具...");
} content.clear();
load();
/** }
* 获取物品汉化名称
* /**
* @param iname * 获取物品汉化名称
* 物品类型名称 *
* @return 物品名称 * @param iname
*/ * 物品类型名称
private static String getItemName(String iname) { * @return 物品名称
String aname = content.get(iname); */
if (aname == null) { private static String getItemName(String iname) {
aname = iname; String aname = content.get(iname);
if (custom != null) { if (aname == null) {
custom.set(iname, iname); aname = iname;
custom.save(); if (custom != null) {
} custom.set(iname, iname);
} custom.save();
return aname; }
} }
return aname;
/** }
* 获取物品类型名称
* /**
* @param i * 获取物品类型名称
* 物品实体 *
* @return 物品类型 * @param i
*/ * 物品实体
private static String getItemType(ItemStack i) { * @return 物品类型
String name = i.getType().name(); */
String dura = ""; private static String getItemType(ItemStack i) {
if (i.getType() == Material.MONSTER_EGG) { String name = i.getType().name();
name = ((SpawnEgg) i.getData()).getSpawnedType().name(); String dura = "";
} else { if (i.getType() == Material.MONSTER_EGG) {
int dur = i.getDurability(); try {
dura = (i.getMaxStackSize() != 1 && dur != 0) ? Integer.toString(dur) : ""; name = ((SpawnEgg) i.getData()).getSpawnedType().name();
} } catch (NullPointerException npe) {
return (name + (dura.isEmpty() ? "" : "-" + dura)).toUpperCase(); name = ((SpawnEggMeta) i.getItemMeta()).getSpawnedType().name();
} }
} else {
/** int dur = i.getDurability();
* 载入数据 dura = (i.getMaxStackSize() != 1 && dur != 0) ? Integer.toString(dur) : "";
*/ }
private static void load() { return (name + (dura.isEmpty() ? "" : "-" + dura)).toUpperCase();
new Thread(() -> { }
try {
Map<String, String> local = YumConfig.getLocal(CONFIG_NAME).getContentMap(); /**
if (local != null) { * 载入数据
Log.i("本地汉化文件词条数量: " + local.size()); */
content.putAll(local); private static void load() {
} new Thread(() -> {
Map<String, String> remote = YumConfig.getRemote(CONFIG_NAME).getContentMap(); try {
if (remote != null) { Map<String, String> local = YumConfig.getLocal(CONFIG_NAME).getContentMap();
Log.i("远程汉化文件词条数量: " + remote.size()); if (local != null) {
content.putAll(remote); Log.i("本地汉化文件词条数量: " + local.size());
} content.putAll(local);
Log.i("本地化工具初始化完毕..."); }
} catch (Exception e) { Map<String, String> remote = YumConfig.getRemote(CONFIG_NAME).getContentMap();
Log.w("本地化工具初始化失败: %s %s", e.getClass().getName(), e.getMessage()); if (remote != null) {
Log.d(CONFIG_NAME, e); Log.i("远程汉化文件词条数量: " + remote.size());
} content.putAll(remote);
}).start(); }
} Log.i("本地化工具初始化完毕...");
} } catch (Exception e) {
Log.w("本地化工具初始化失败: %s %s", e.getClass().getName(), e.getMessage());
Log.d(CONFIG_NAME, e);
}
}).start();
}
}