Home > other >  avoid duplication in Java due to auto generated similar classes
avoid duplication in Java due to auto generated similar classes

Time:12-13

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.

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related