欢迎来到Minecraft插件百科!
对百科编辑一脸懵逼?
帮助:快速入门
带您快速熟悉百科编辑!
因近日遭受攻击,百科现已限制编辑,有意编辑请加入插件百科企鹅群:223812289
查看“用户:Laxcat”的源代码
←
用户:Laxcat
跳转到导航
跳转到搜索
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于这些用户组的用户执行:
用户
、
自动确认用户
、
巡查者
您可以查看和复制此页面的源代码。
== 个人信息 == *一个业余的插件作者 废柴 *能够编写插件 *但是对于Java的了解不够深入 #MCBBS ID: q513902026 #Github ID: HopeAsd(q513902026) #Github: [http://github.com/q513902026 我的GitHub页面] == 代码预留地 == === 搜索你插件中所有特定包开头的class文件 === [https://github.com/q513902026/HopeCore/blob/main/src/main/java/me/hope/core/inject/InjectFinder.java#L21-L51 InjectFinder] <source lang="java"> @NotSinglethon public class InjectFinder { private static JarFile jarfile; public static <T extends JavaPlugin> Collection<Class<?>> getClasses(T plugin, String rootPackage, boolean recursive) { Set<Class<?>> classes = Sets.newHashSet(); String packDirName = rootPackage.replace('.', '/'); Enumeration<URL> dirs; try{ dirs = plugin.getClass().getClassLoader().getResources(packDirName); while(dirs.hasMoreElements()){ URL url = dirs.nextElement(); String protocol = url.getProtocol(); switch(protocol){ case "file": String filePath = URLDecoder.decode(url.getFile(),"UTF-8"); classes.addAll(findClassesByFile(rootPackage,filePath,recursive)); break; case "jar": JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jar = conn.getJarFile(); if (jar == null){ jar = jarfile; }else{ jarfile = jar; } classes.addAll(findClassesByJar(rootPackage,jar,recursive)); break; } } }catch(IOException e){ } return classes; } private static Collection<Class<?>> findClassesByJar(String rootPackage,JarFile jarFile,boolean recursive){ Set<Class<?>> classes = Sets.newHashSet(); Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries(); String packDirName = rootPackage.replace('.', '/'); while(jarEntryEnumeration.hasMoreElements()){ JarEntry jarEntry = jarEntryEnumeration.nextElement(); String name = jarEntry.getName(); if('/' == name.charAt(0)){ name = name.substring(1); } if(name.startsWith(packDirName)){ int index = name.lastIndexOf('/'); if(index != -1 ){ rootPackage = name.substring(0,index).replace('/','.'); } if((index != -1) || recursive){ if(name.endsWith(".class") && !(jarEntry.isDirectory())){ String className = name.substring(rootPackage.length()+1,name.length()-6); try { Class clazz = getClass(rootPackage,className); if (clazz != null){ classes.add(clazz); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } } return classes; } private static Collection<Class<?>> findClassesByFile(String rootPackage,String filePath,boolean recursive){ Set<Class<?>> classes = Sets.newHashSet(); findAndAddClasses(rootPackage,filePath,recursive,classes); return classes; } private static void findAndAddClasses(String rootPackage,String filePath,boolean recursive,Collection<Class<?>> classes){ File dir = new File(rootPackage); if(!dir.exists() || !dir.isDirectory()){ return; } File[] dirFiles = dir.listFiles(pathname -> (recursive && pathname.isDirectory()) || (pathname.getName().endsWith(".class"))); for(File file:dirFiles){ if(file.isDirectory()){ findAndAddClasses(rootPackage+"."+file.getName(),file.getAbsolutePath(),recursive,classes); }else{ String className =file.getName().substring(0,file.getName().length()-6); try{ Class clazz = getClass(rootPackage,className); if (clazz != null){ classes.add(clazz); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } private static Class<?> getClass(String rootPackage,String className) throws ClassNotFoundException { Class clazz = Class.forName(rootPackage + '.' + className); return clazz.isAnnotationPresent(NotSinglethon.class) ? null:clazz; } } </source> 使用方法 <source lang="java"> Set<Class<?>> classes = InjectFinder.getClasses(pluginInstance,"packageName",isRecursive) <source> pluginInstance 需要你自己插件的实例 packageName 指搜索的指定包的文件 isRecursive 指是否循环 === 继承此类自动在实例化时注册监听器 === BaseListener.java <source lang="java">package io.bilicraft.r6.bbs.listener; import java.util.logging.Logger; import org.bukkit.event.Listener; import io.bilicraft.r6.bbs.BiliBS; /** * 父类 继承后请设定为无参构造 * * @author HopeAsd * */ public class BaseListener implements Listener { private String name; private final String version; private Logger logger = BiliBS.getInstance().getLogger(); private boolean debug = false; /** * 请务必保证构造为无参构造 否则会注册失败 * * @param name * 监听器的名字 * @param version * 监听器的版本 */ public BaseListener(String name, final String version) { this.name = name; this.version = version; BiliBS.addListener(name, this); } /** * 调用此方法可以往服务端发送信息 自动标示监听器名字 * * @param strings */ protected void sendConsoleMessage(String... strings) { StringBuilder sBuilder = new StringBuilder(); for (String s : strings) { sBuilder.append(s + "\n"); } logger.info("[" + name + "]:" + sBuilder.toString()); } /** * 获取监听器版本 * * @return 监听器的版本 */ public final String getVersion() { return version; } /** * 是否为debug输出模式 * * @return 是否为debug输出模式 */ public boolean isDebug() { return debug; } /** * 更改debug输出模式 */ public void setDebug() { debug = !debug; } /** * 使用此方法用于注册监听器和反注册监听器 * * @return 监听器名字 */ public String getName() { return this.name; } } </source> ==== Example BaseListener ==== <source lang="java"> package io.bilicraft.r6.bbs.listener; import org.bukkit.Chunk; import org.bukkit.entity.Entity; import org.bukkit.entity.Zombie; import org.bukkit.event.EventHandler; import org.bukkit.event.world.ChunkUnloadEvent; /** * 管理实体的监听器 * @author HopeAsd * */ public class EntityListener extends BaseListener { private static boolean debug = false; public EntityListener() { super("EntityListener","v0.1.0"); } @EventHandler public void onChunkUnloadEvent(ChunkUnloadEvent event) { Chunk chunk = event.getChunk(); for (Entity entity : chunk.getEntities()) { if (isClearEntity(entity)) { if (debug) { sendConsoleMessage("Entity: " + entity.getType() + "Location:{x:" + (int) entity.getLocation().getX() + ",y:" + (int) entity.getLocation().getY() + ",z:" + (int) entity.getLocation().getZ() + "}"); ; } entity.remove(); } } } public static boolean isClearEntity(Entity entity) { switch (entity.getType()) { case ZOMBIE: if (((Zombie) entity).isVillager()) { return false; } case CREEPER: case SKELETON: case SPIDER: case CAVE_SPIDER: case SQUID: case PIG_ZOMBIE: return true; default: break; } return false; } } </source> === 对所有继承BaseListener的实例进行操作 === BiliBS.java <source lang="java">package io.bilicraft.r6.bbs; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import io.bilicraft.r6.bbs.listener.BaseListener; public class BiliBS extends JavaPlugin implements Listener { private static BiliBS instance; private static HashMap<String, BaseListener> enableListenerList = new HashMap<String, BaseListener>(); private static HashMap<String, BaseListener> disableListenerList = new HashMap<String, BaseListener>(); @Override public void onEnable() { instance = this; try { ListenerFactory.main(null); } catch (Exception e) { getLogger().info("加载监听类错误" + e.getClass().getName()); } ; getServer().getPluginManager().registerEvents(this, this); // System.out.println("["+BiliBS.class.getName()+"]: // "+getServer().getBukkitVersion()); registerListeners(); registerCommands(); } @Override public void onDisable() { instance = null; } public static BiliBS getInstance() { return instance; } private void registerCommands() { getCommand("bilibs").setExecutor(new BilibsCommand()); } private void registerListeners() { for (BaseListener listener : enableListenerList.values()) { getServer().getPluginManager().registerEvents(listener, instance); getLogger().info("Listener:" + listener.getName() + "<" + listener.getVersion() + ">" + "注册完成 ,debug:" + listener.isDebug()); } } public static void registerListener(BaseListener baseListener) throws Exception { if (disableListenerList.containsKey(baseListener.getName())) { disableListenerList.remove(baseListener.getName(), baseListener); BaseListener listener = baseListener.getClass().newInstance(); BiliBS.getInstance().getServer().getPluginManager().registerEvents(listener, instance); BiliBS.getInstance().getLogger().info("Listener:" + listener.getName() + "<" + listener.getVersion() + ">" + "注册完成 ,debug:" + listener.isDebug()); } } public static void addListener(String name, BaseListener baseListener) { enableListenerList.put(name, baseListener); } public static void removeListener(BaseListener baseListener) { if (enableListenerList.containsKey(baseListener.getName())) { enableListenerList.remove(baseListener.getName(),baseListener); disableListenerList.put(baseListener.getName(), baseListener); HandlerList.unregisterAll(baseListener); } } public static StringBuilder getListenerList() { StringBuilder sBuilder = new StringBuilder(ChatColor.GREEN + "[BiliBS]: \nListenerList:"); sBuilder.append("["); for (String listenerName : enableListenerList.keySet()) { sBuilder.append(ChatColor.GREEN + listenerName + "<"+enableListenerList.get(listenerName).isDebug()+">,"); } for (String listenerName : disableListenerList.keySet()) { sBuilder.append(ChatColor.RED + listenerName + "<"+disableListenerList.get(listenerName).isDebug()+">,"); } sBuilder.append("]"); return sBuilder; } public static BaseListener getEnableListener(String key) { return enableListenerList.get(key); } public static BaseListener getDisableListener(String key) { return disableListenerList.get(key); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { return super.onCommand(sender, command, label, args); } } </source>
返回
用户:Laxcat
。
导航菜单
个人工具
登录
命名空间
用户页
讨论
大陆简体
查看
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
编辑相关
百科公告
编辑帮助
互助客栈
贡献分数
测试沙盒
发布条目
插件分类
管理
安全
聊天
编程
经济
修正
娱乐
综合
信息
机械
角色
传送
网页
整地
创世
付费
其它
工具
链入页面
相关更改
用户贡献
日志
查看用户组
特殊页面
页面信息
相关网站
MCMOD百科
Minecraft中文百科
Minecraft纪念论坛
Minecraft百度贴吧
虚无世界Wiki