微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 2 个补充模块让一个简单的 ServiceLoader 在 Java 中工作

如何解决使用 2 个补充模块让一个简单的 ServiceLoader 在 Java 中工作

我对使用 ServiceLoader 还很陌生,我正在尝试启动并运行一个非常简单的示例。

目前有 4 个模块:BLCore、BLInterface、BLMod1、BLMod2

BLCore depends on: BLInterface,BLMod1,BLMod2
BLInterface depends on: Nonne
BLMod1 depends on: BLInterface
BLMod2 depends on: BLInterface

BLCore 包含主要方法并包含以下内容

import java.util.ServiceLoader;

public class Main {
    public static void main(String[] args) {
        for(BeanInterface val : ServiceLoader.load(BeanInterface.class)){
            System.out.println("You are a "+val.getName());
        }
    }
}

而且 BLInterface 有一个 String 方法,它只打印出一个名字左右。

结构如下:

代码可以编译但是ServiceLoader没有检测到Module1和Module2,有什么想法吗?

----状态---- 已删除所有错误,但仍无法正常工作。

解决方法

您应该使用包而不是默认包。例如BLMod1

在 Java 8 中(排除由模块引起的问题):

  • META-INF/services/com.example.BeanInterface 项目中,com.example.Module1 必须包含 BLMod2
  • META-INF/services/com.example.BeanInterface 项目中,com.example.Module2 必须包含 BLCore
  • BLMod1 配置(Maven、Gradle 甚至您的 IDE)中,您必须确保引用 BLMod2Module1:当您执行您的主要的。
  • 确保 Module2module-info.java 具有公共构造函数。

如果您使用的是 Java 9++,您可能还需要在 module com.example.module1 { provides com.example.BeanInterface with com.example.Module1; } 中添加适当的行:

import discord
from discord.ext import commands

class voice(commands.Cog):
    def __init__(self,client):
        self.client = client

    @commands.Cog.listener()
    async def on_voice_state_update(self,member,before,after):
        channel = before.channel or after.channel

        if channel.id == Channel_ID:
            if before.channel is None and after.channel is not None: # Member joins the defined channel
                role = discord.utils.get(member.guild.roles,id=Role_ID)
                await member.add_roles(role) # Role is given
            elif before.channel is not None and after.channel is None:
                role = discord.utils.get(member.guild.roles,id=Role_ID)
                await member.remove_roles(role) # Role removed because he left the channel
                
def setup(client):
    client.add_cog(voice(client))

这就是包的用处:如果没有合适的包,您可能无法使用模块。

您可能还想阅读 Javadoc:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ServiceLoader.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。