简体   繁体   English

由于自动生成相似的类,避免在 Java 中重复

[英]avoid duplication in Java due to auto generated similar classes

Multiple instances多个实例

Each FaultType comes from a different package.每个 FaultType 来自不同的包。 For example例如

com.test.package1.FaultType com.test.package1.FaultType

and

com.test.package2.FaultType com.test.package2.FaultType

are exactly identical (but this might change in the future).完全相同(但这在未来可能会改变)。 These classes are auto generated and cannot be modified.这些类是自动生成的,不能修改。 I have created a custom internal class我创建了一个自定义内部类

public class CustomFault {

    private String type;
    private int number;
    private String description;
    private String retryAfter;
    private String system;
    private String nativeError;
    private String nativeDescription;

that will be created by copying values from FaultType to CustomFault.将通过将值从 FaultType 复制到 CustomFault 来创建。

My goal is to avoid code duplication.我的目标是避免代码重复。 So I want to create a common method that will return a new instance of CustomFault by using generic code instead of my current situation.所以我想创建一个通用方法,该方法将使用通用代码而不是我当前的情况返回 CustomFault 的新实例。

CustomFault transformFault(com.test.package1.FaultType fault) {
 //duplicate code here
}

CustomFault transformFault(com.test.package2.FaultType fault) {
 //duplicate code here
}

CustomFault transformFault(com.test.package3.FaultType fault) {
 //duplicate code here
}

How can I do it in Java (my current version is Java 8).我怎样才能用 Java 做到这一点(我当前的版本是 Java 8)。

I have tried to use generics, without luck.我曾尝试使用泛型,但没有成功。

As long as the generated classes don't have anything in common, you can't.只要生成的类没有任何共同点,就不能。 Even though the fields look the same, Java has no way of addressing them in the same way.尽管字段看起来相同,但 Java 无法以相同的方式对它们进行寻址。

The easiest solution is to have code that looks like it's duplicate but operates on different classes, as you've already mentioned in the question.正如您在问题中已经提到的那样,最简单的解决方案是使用看起来重复但在不同类上运行的代码。

The clean solution is to change the code that generates those FaultType classes.干净的解决方案是更改生成那些FaultType类的代码。 Either also generate the code that converts to a single CustomFault class, or have the FaultTypes implement an interface, so you can implement your conversion code using that.也可以生成转换为单个CustomFault类的代码,或者让FaultTypes实现一个接口,这样您就可以使用它来实现您的转换代码。

You could construct something like that using relfection, but you most certainly should not attempt this.您可以使用反射构建类似的东西,但您绝对不应该尝试这样做。

If you have control over the generated code then use an interface, as mentioned earlier.如果您可以控制生成的代码,那么请使用一个接口,如前所述。 Otherwise just accept the reality of writing this boilerplate code.否则就接受编写此样板代码的现实。

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

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