简体   繁体   English

在 Java 中向下转型? 这是一个令人沮丧的问题吗?

[英]Downcasting in Java ? Is this a downcasting issue at all?

So I have a POJO class let´s call it: InnerDomainObject.所以我有一个 POJO 类,我们称之为:InnerDomainObject。 Then I have an object representing this object, with a few more fields, for communication towards different clients (it s an API DTO): OuterDomainObject然后我有一个代表这个对象的对象,还有几个字段,用于与不同客户端的通信(它是一个 API DTO):OuterDomainObject

Because the DTO has in fact all of the POJOs fields, I made OuterDomainObject inherit from InnerDomainObject.因为 DTO 实际上拥有所有 POJO 字段,所以我让 OuterDomainObject 继承自 InnerDomainObject。

Now I need to somehow cast InnerDomainObject to OuterDomainObject --> not possible.现在我需要以某种方式将 InnerDomainObject 转换为 OuterDomainObject --> 不可能。

I want to avoid writing a constructor iterating through all the fields.我想避免编写一个遍历所有字段的构造函数。 I want to avoid writing useless code.我想避免编写无用的代码。

I just want OuterDomainObject to be created out of InnerDomainOBject´s values and then add some to it before sending it to the client.我只想从 InnerDomainOBject 的值中创建 OuterDomainObject,然后在将其发送到客户端之前添加一些值。

What´s the best way of doing this ?这样做的最佳方法是什么?

You sound like you are using the Adapter Pattern .您听起来像是在使用Adapter Pattern You shouldn't need to cast an InnerDomainObject to an OuterDomainObject.您不需要将 InnerDomainObject 转换为 OuterDomainObject。 You should use composition: the OuterDomainObject should hold a reference to an InnerDomainObject, which will likely be passed into a constructor.您应该使用组合:OuterDomainObject 应该持有对 InnerDomainObject 的引用,该引用可能会被传递到构造函数中。 When a client invokes a method on an OuterDomainObject, if that method exists in InnerDomainObject, the OuterDomainObject should call that method on its instance of InnerDomainObject.当客户端调用 OuterDomainObject 上的方法时,如果该方法存在于 InnerDomainObject 中,则 OuterDomainObject 应在其 InnerDomainObject 实例上调用该方法。 Instead of casting an InnerDomainObject foo to an OuterDomainObject, just create a new OuterDomainObject and pass in foo : new OuterDomainObject(foo) .不要将 InnerDomainObject foo转换为 OuterDomainObject,只需创建一个新的 OuterDomainObject 并传入foonew OuterDomainObject(foo) You will need to write some simple glue code, but the result is very clean.您将需要编写一些简单的粘合代码,但结果非常干净。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM