简体   繁体   中英

avoid duplication in Java due to auto generated similar classes

Multiple instances

Each FaultType comes from a different package. For example

com.test.package1.FaultType

and

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.

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 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).

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.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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