在Java中将一个类的对象转换为另一个类的对象。

huangapple go评论135阅读模式
英文:

Convert object from one class to another in java

问题

我有2个自定义类A和B。
现在我有一个A类的对象,假设为'a',我必须将它转换为B类。

现在我有两种方法:

  • 第一种是编写一个转换工具类,其中有一个用于转换的静态方法。
  • 第二种方法是在类A中编写具有方法convertToB()的逻辑。

哪种方法更准确。请给予建议。

英文:

I have 2 custom classes A and B.
Now I have an object of A let say 'a' and have to convert it to B class.

Now I have 2 approach

  • First is I write a transform Util which has a static method for conversion.
  • The second approach is to write that logic in class A with a method convertToB()

Which one is more accurate. Please suggest.

答案1

得分: 1

总之,这取决于A和B之间的关系。

如果B扩展了A,则在将A对象分配给B对象时,转换会在语言内部完成。

否则,如果没有继承关系,建议要么创建一个实用类来在将来更改时进行转换,要么使B的构造函数接受A对象作为参数。

英文:

In short, it depends on the relationship between A and B.

If B extends A the conversion is done within the language when assigning an A object to a B object.

Otherwise, if there is no inheritance at play, it would be advised to either create a util class to do the conversion for the case of future changes, or have a constructor of B that has an A object as a parameter.

答案2

得分: 0

这是偏好问题,也许更适合于软件工程/设计领域的Stack Overflow的对应部分。话虽如此,我会选择第一个选项。如果您将来添加更多的类并且需要在它们之间进行转换,您将会使您的类膨胀,其中包含了所有的转换方法。如果您有一个或多个带有转换方法的类,代码会更清晰。

英文:

This is a matter of preference and a question perhaps better suited for the software engineering/design counterpart to Stack Overflow. That said, I would use the first option. If you ever add more classes and need to convert between them, you will bloat your classes with all the conversion methods. If you have one or more classes with the conversion methods, the code is cleaner.

答案3

得分: 0

Concerns 的分离 - util 类是最佳方法

英文:

Separation of Concerns - util class is the best approach

huangapple
  • 本文由 发表于 2020年8月24日 21:34:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63562126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定