如何使用 java 8 可选提取 Json 对象

How to use java 8 Optional to extract Json Object

我正在学习 java8 函数式编程,我正在学习可选的 Lambda。

JSONParser parser = new JSONParser();
Object Obj = parser.parse(new FileReader("demoprgmsv1.json"));
JSONObject jsonObject = (JSONObject) Obj;
JSONArray array = new JSONArray();
array.add(jsonObject.get("params"));
String functionPath = (String) jsonObject.get("function");
String className= functionPath.substring(0,functionPath.lastIndexOf('.'));
String functionName = functionPath.substring(functionPath.lastIndexOf('.') + 1,functionPath.length() - 2);
Object test= Class.forName(className).newInstance();
method1 = test.getClass().getDeclaredMethod(functionName, JSONArray.class).invoke(test,array);

这段代码是获取写在JSON文件中的函数名和参数并执行
我试图使用可选的 lambda 分两三行更改此代码以避免 try catch 块。

 Object obj=  Optional
                  .ofNullable(parser.parse(new FileReader("DemoProgram.json")))
                  .orElseThrow(FileNotFoundException::new);

我试过这样重写。但没有得到结果.. 请指教....

您可能想要捕获这些异常并将它们包装成一个,您不需要 Optional.

  • FileReader 如果找不到文件
  • 已经抛出 FileNotFoundException
  • JSONParser 如果面对 IOException
  • 已经抛出 ParseException
try {
    JSONParser parser = new JSONParser();
    Object Obj = parser.parse(new FileReader("demoprgmsv1.json"));
    JSONObject jsonObject = (JSONObject) Obj;
    // ...
} catch (ParseException | FileNotFoundException exception) {
    throw new IOException(exception); // or better a custom exception
}

后续调用 可以通过 Optional 调用链处理。只要存在多种异常类型,您可能只想抛出一种自定义异常(取决于首选设计)。

JSONObject jsonObject = (JSONObject) Obj;
JSONArray array = Optional.ofNullable(jsonObject.get("params"))
    // appendElement(..) is same to add(..) + return this
    .map(obj -> new JSONArray().appendElement(obj))
    .orElseGet(JSONArray::new);                                    // an empty array

String className = Optional.ofNullable(jsonObject.get("function"))
    .map(Object::toString)
    .map(f -> f.substring(0, f.lastIndexOf('.')))
    .orElseThrow(ClassNotFoundException::new);                     // a type is up to you
            
String functionName = Optional.of(className)
    .map(f -> f.substring(f.lastIndexOf('.') + 1, f.length() - 2))
    .orElseThrow(NoSuchMethodException::new);                      // a type is up to you

// at this point both className and functionName exist
// you might want to check the emptyness, though
// also, newInstance is deprecated, better use getDeclaredConstructor

Object test = Class.forName(className).newInstance();
Method method = test.getClass().getDeclaredMethod(functionName, JSONArray.class);
Object returnedObject = method.invoke(test,array);