Objects.requireNonNull( )方法说明

本文详细介绍了Java中Objects.requireNonNull方法的用法,此方法用于在方法中进行参数验证,确保对象不为空,避免空指针异常。通过具体示例展示了如何在代码中应用此方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.方法介绍

有时候,我们为了使得对象不为空,可以使用Objects.requireNonNull( )方法对对象进行判断。

2.源代码
     /* @param obj 需要检测是否为空的对象
     * @param <T> 对象类型
     * @return 对象不为空则返回该对象
     * @throws 对象为空则报NullPointerException异常
     */
    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }
3.使用说明

此方法主要用于在方法中进行参数验证。遇到要判断对象是否为空,空的时候报空指针异常的时候就可以使用这个方法。

      public Foo(Bar bar) {
          this.bar = Objects.requireNonNull(bar);
      }
public class Main { public static void main(String[] args) { try{ //获取access token DefaultWeLinkClient authClient = new DefaultWeLinkClient("https://open.welink.huaweicloud.com/api/auth/v2/tickets"); AuthV2TicketsRequest authRequest = new AuthV2TicketsRequest(); authRequest.setClientId("20250305170838530878252"); authRequest.setClientSecret("69aa9b46-cd86-e8e9-3520-43c6970af251"); AuthV2TicketsResponse rsp = authClient.execute(authRequest); //向群组中发送文件 DefaultWeLinkClient client = new DefaultWeLinkClient("https://open.welink.huaweicloud.com/api/welinkim/v1/im-service/chat/group-chat"); WelinkIMV1ImServiceChatGroupChatRequest req = new WelinkIMV1ImServiceChatGroupChatRequest(); req.setAccessToken(rsp.getAccessToken()); File directory = new File("H:/XiyuanLiQ04547"); if (!directory.exists() || !directory.isDirectory()) { throw new RuntimeException("指定目录不存在: " + directory.getAbsolutePath()); } File newestFile = Arrays.stream(Objects.requireNonNull(directory.listFiles())) .filter(File::isFile) // 过滤掉子目录 .max(Comparator.comparingLong(File::lastModified)) .orElseThrow(() -> new RuntimeException("目录中没有文件")); req.setFile(newestFile); // req.setFile(new File("H:/XiyuanLiQ04547/BCD针卡KEY参数Summary_Run520.pptx")); WelinkIMV1ImServiceChatGroupChatRequest.AppServiceInfo appServiceInfo = new WelinkIMV1ImServiceChatGroupChatRequest.AppServiceInfo(); appServiceInfo.setAppServiceId("20250305170838530878252"); appServiceInfo.setAppServiceName("test"); req.setAppServiceInfo(appServiceInfo); req.setAppMsgId(UUID.randomUUID().toString()); //消息标识,全局唯一,建议使用UUID List<String> reqGroupIdList = new ArrayList<>(); reqGroupIdList.add("733039044082045012"); req.setGroupId(reqGroupIdList); req.setIsPush(true); req.setClientAppId("1"); req.setContentType(4);// 根据消息内容类型填写对应值 WelinkIMV1ImServiceChatGroupChatResponse msgResponse = null; msgResponse = client.uploadAndSend(req); } catch (IOException | ApiException e) { System.out.println(e.getMessage()); e.printStackTrace(); // 打印完整错误堆栈 } } } 选择目录中最新的文件。并在发送完之后,删除文件
03-11
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值