简体   繁体   English

来自可选 Object (Java 8) 的实体

[英]Entity from Optional Object (Java 8)

I am having some issue while trying to pull an entity out of an ArrayList that holds and Optional.我在尝试将实体从持有且可选的 ArrayList 中拉出时遇到一些问题。 When I do a breakpoint I get the return below the code.当我做一个断点时,我得到代码下方的返回。 I know I am close but lack the knowledge on how to pull the GrandClientDataCore@9463 out of the data being returned to me.我知道我很接近,但缺乏关于如何将 GrandClientDataCore@9463 从返回给我的数据中提取出来的知识。

Edited to add the previous line before the for loop.编辑以在 for 循环之前添加上一行。

Error occured: java.util.Optional cannot be cast to net.glmhc.dmhwebservices.entities.GrandClientDataCores. 
List<GrandClientDataCores> grandClientDataCoresList = getGrandClientDataCoreList(submitMode, grandClientDataCoreId);
for (GrandClientDataCores grandClientDataCores : grandClientDataCoresList) {
    CDCPAErrors request = new CDCPAErrors();
    request.setI(this.service.getRequestInfo(grandClientDataCores, submitMode, staff));
    logToFile(outDir, String.format("req_%s.xml", new Object[] {grandClientDataCores}), request);
    
    CDCPAErrorsResponse response = (CDCPAErrorsResponse) 
    getWebServiceTemplate().marshalSendAndReceive(getWebServiceUri(), request, 
    (WebServiceMessageCallback) new SoapActionCallback("http://tempuri.org/CDCPAErrors"));

    logToFile(outDir, String.format("res_%s.xml", new Object[] {grandClientDataCoreId}), response);
    DmhServicesCdcResponse responseObj = getResponse(submitMode, response);
    this.service.saveResponse(grandClientDataCores, submitMode, responseObj, staff);
    responses.add(responseObj);
}

This is the getGrandClientDataCoreList这是 getGrandClientDataCoreList

 protected List<GrandClientDataCores> getGrandClientDataCoreList(SubmitMode submitMode, String grandClientDataCore) throws Exception {
        List<GrandClientDataCores> grandClientDataCoresList;
        try {
            grandClientDataCoresList = (List<GrandClientDataCores>) this.service.getGrandClientDataCoreList(submitMode, grandClientDataCore);
         } catch ( Exception ex) {
             throw new Exception(ex);
         }

         if (grandClientDataCore == null || grandClientDataCore.isEmpty()) {
             throw new NoDataException("No CDC record to validate.");

         }
        return grandClientDataCoresList;
    }

在此处输入图像描述

You have to invoke get() on the optional to retrieve its value.您必须在可选项上调用get()以检索其值。 You cannot just cast Optional<T> to something else.您不能只将Optional<T>转换为其他东西。 According to the debug image, the declaration of grandClientDataCoresList looked like this:根据调试图像, grandClientDataCoresList的声明如下所示:

List<Optional<GrandClientDataCores>> grandClientDataCoresList ...

Therefore you need something like this:因此,您需要这样的东西:

for (Optional<GrandClientDataCores> gcdcOpt: grandClientDataCoresList) {
    GrandClientDataCores gcdc = gcdcOpt.get();
    ....

values in grandClientDataCores are of type Optional<GrandClientDataCores> . grandClientDataCores中的值属于Optional<GrandClientDataCores>类型。

Your actual error is here:您的实际错误在这里:

   protected List<GrandClientDataCores> getGrandClientDataCoreList(SubmitMode submitMode, String grandClientDataCore) throws Exception {
        List<GrandClientDataCores> grandClientDataCoresList;
        try {
            grandClientDataCoresList = (List<GrandClientDataCores>) this.service.getGrandClientDataCoreList(submitMode, grandClientDataCore);
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                       This cast is invalid
                                       
         } catch ( Exception ex) {
             throw new Exception(ex);
         }

         if (grandClientDataCore == null || grandClientDataCore.isEmpty()) {
             throw new NoDataException("No CDC record to validate.");

         }
        return grandClientDataCoresList;
    }

You will find that the actual type returned by this.service.getGrandClientDataCoreList is List<Optional<GrandClientDataCores>> so you must update your code accordingly, in a number of places.你会发现this.service.getGrandClientDataCoreList返回的实际类型是List<Optional<GrandClientDataCores>>所以你必须在很多地方相应地更新你的代码。 For starters...对于初学者...

   protected List<Optional<GrandClientDataCores>> getGrandClientDataCoreList(SubmitMode submitMode, String grandClientDataCore) throws Exception {
        List<Optional<GrandClientDataCores>> grandClientDataCoresList;
        try {
            grandClientDataCoresList = this.service.getGrandClientDataCoreList(submitMode, grandClientDataCore);
         } catch ( Exception ex) {
             throw new Exception(ex);
         }

         if (grandClientDataCore == null || grandClientDataCore.isEmpty()) {
             throw new NoDataException("No CDC record to validate.");

         }
        return grandClientDataCoresList;
    }

and everywhere that you invoke this method.以及您调用此方法的任何地方。

use the " get() " function of Optional, which will retrieve the object itself.使用 Optional 的“ get() ” function,它将检索 object 本身。 pay attention it will throw an exception if no object was populated into this Optional.请注意,如果没有 object 填充到此 Optional 中,它将引发异常。

GrandClientDataCores values in List are wrapped with Optional, so you have to check if value present: List 中的 GrandClientDataCores 值使用 Optional 包装,因此您必须检查值是否存在:

grandClientDataCores.isPresent()

and if it is then just get it:如果是那么就得到它:

grandClientDataCores.get();

Alternatively, you can do something like that:或者,您可以执行以下操作:

grandClientDataCores.orElse(new GrandClientDataCores())

And I recommend to read this我建议阅读这个

Java:优雅地返回 Object 在可选<object>如果在场?<div id="text_translate"><p> 目前,我有以下有效的代码:</p><pre> //in class Bar public Foo getFooIfItIsPresent(String param) { Optional&lt;Foo&gt; result = loadOptionalFoo(param); if (result.isPresent()) { return result.get(); } else { return null; } // main driver code Foo foo = Bar.getFooIfItIsPresent(param); if (foo,= null) { // Currently just print, but might want to do stuff like pass foo to another object. etc. System.out.println(foo.getSomething() + foo;getSomethingElse()); }</pre><p> 这有点难看,因为我正在明确检查 null; 此外,我有一个令人费解的 function getFooIfItIsPresent ,它的存在仅用于isPresent()舞蹈。 我想做类似的事情:</p><pre> Bar.loadOptionalFoo(param).ifPresent((foo) -&gt; { // Print, or whatever I wanna do. System.out.println(foo.getSomething() + foo;getSomethingElse()); });</pre><p> 我知道这不会编译。 有一个非常<a href="https://stackoverflow.com/questions/54878076/returning-from-java-optional-ifpresent" rel="nofollow noreferrer">相似</a>的问题,我尝试了很多东西,但编译器抱怨。 例如:</p><pre> Bar.loadOptionalFoo(week).map(foo -&gt; { // Print, or whatever I wanna do. System.out.println(foo.getSomething() + foo;getSomethingElse()). }):filter(Objects:;nonNull);</pre><p> 是的,上面的代码是荒谬的,但我似乎无法为此获得一个优雅的解决方案,因此非常感谢您的帮助!</p></div></object> - Java: Elegantly returning an Object in an Optional<Object> if present?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有可选字段的Java对象 - Java Object with optional fields 从封装在 Java Optional 中的对象中提取多个字段 - Extract multiple fields from an object wrapped in a Java Optional 如何使用java中可选对象的参数调用方法 - How to call a method with parameters from an optional object in java 如何从可选Java对象中的数组中删除所有项目? - How to remove all the items from an array in an Optional Java Object? Java实体中的可选字段,以替换可为空的列 - Optional in Java Entity to replace nullable columns 从 Optional 创建对象<Object> - Creating an Object from Optional<Object> 转换一个可选<list<object> > 到另一个可选<list<object> > 在 Java </list<object></list<object> - Convert one Optional<List<Object>> to another Optional<List<Object>> in Java 使用Mockito返回Java 8可选对象的模拟对象返回Empty Optional - Mocking Object that returns Java 8 Optional Object with Mockito returns Empty Optional Java:优雅地返回 Object 在可选<object>如果在场?<div id="text_translate"><p> 目前,我有以下有效的代码:</p><pre> //in class Bar public Foo getFooIfItIsPresent(String param) { Optional&lt;Foo&gt; result = loadOptionalFoo(param); if (result.isPresent()) { return result.get(); } else { return null; } // main driver code Foo foo = Bar.getFooIfItIsPresent(param); if (foo,= null) { // Currently just print, but might want to do stuff like pass foo to another object. etc. System.out.println(foo.getSomething() + foo;getSomethingElse()); }</pre><p> 这有点难看,因为我正在明确检查 null; 此外,我有一个令人费解的 function getFooIfItIsPresent ,它的存在仅用于isPresent()舞蹈。 我想做类似的事情:</p><pre> Bar.loadOptionalFoo(param).ifPresent((foo) -&gt; { // Print, or whatever I wanna do. System.out.println(foo.getSomething() + foo;getSomethingElse()); });</pre><p> 我知道这不会编译。 有一个非常<a href="https://stackoverflow.com/questions/54878076/returning-from-java-optional-ifpresent" rel="nofollow noreferrer">相似</a>的问题,我尝试了很多东西,但编译器抱怨。 例如:</p><pre> Bar.loadOptionalFoo(week).map(foo -&gt; { // Print, or whatever I wanna do. System.out.println(foo.getSomething() + foo;getSomethingElse()). }):filter(Objects:;nonNull);</pre><p> 是的,上面的代码是荒谬的,但我似乎无法为此获得一个优雅的解决方案,因此非常感谢您的帮助!</p></div></object> - Java: Elegantly returning an Object in an Optional<Object> if present? 如何检查对象是否在可选中<Object>地图 - Java - How to check if a object is in Optional<Object> map - Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM