如何在不使用lambda表达式的情况下使用JSONObject.computeIfAbsent [英] How to use JSONObject.computeIfAbsent without lambda expression

查看:422
本文介绍了如何在不使用lambda表达式的情况下使用JSONObject.computeIfAbsent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我想知道如何在不使用lambda表达式的情况下使用JSONObject.computeIfAbsent. 其实这是我的代码

Hello guys I want to know how can I use JSONObject.computeIfAbsent without the use of lambda expression. Actually, this is my code

list.computeIfAbsent(id, k -> {
            try {
                throw new UnknowClientException("Unkown client : Unable to find client with id" + id);
            } catch (UnknowClientException e) {

            }
        });

我希望函数抛出我的自定义异常.我假设我需要在函数的签名中添加thow,而我不知道要使用lambda表达式来做到这一点,这就是为什么我要使用函数"

I want the function to throw my custom exception. I assume that i need to add thows to the signature of the function and I don't know of to do that with lambda expression that's is why I wan to use a "function"

推荐答案

将lambda表达式转换为普通类没有意义,因为这不会更改允许的异常集.这是已实现的interface,其声明确定了允许的例外.该接口的实现者无法将已检查的异常添加到throws子句中,而该子句尚未被该接口的已声明的子类覆盖.

There is no point in converting the lambda expression into an ordinary class as that doesn’t change the set of permitted exceptions. It’s the implemented interface whose declaration determines the allowed exceptions. Implementors of the interface can’t add checked exception to the throws clause which weren’t covered by already declared ones of the interface.

如果您正在谈论

If you’re talking about the computeIfAbsent method inherited from the Map interface, the method to implement is Function.apply, which doesn’t allow any checked exception.

或者,您可以使用

result = Optional.ofNullable(list.get(id)).orElseThrow(() -> 
    new UnknowClientException("Unkown client : Unable to find client with id" + id));

通用方法 Optional.orElseThrow 声明要抛出提供的Supplier声明要创建的内容,因此,如果UnknowClientException是已检查的异常,则调用者将不得不捕获或声明它,这似乎是您的原始内容意图.

The generic method Optional.orElseThrow declares to throw what the provided Supplier declares to create, so if UnknowClientException is a checked exception, the caller will have to catch or declare it, which seems to be your original intention.

这篇关于如何在不使用lambda表达式的情况下使用JSONObject.computeIfAbsent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆