Home > front end >  Using toString method in Java projection?
Using toString method in Java projection?

Time:12-16

I have the following projection that is used to retrieve data from joined tables. However, as it is interface, when I want to override toString() method, I get "Interface abstract methods cannot have body" error.

To fix the problem, I use getToString method as shown below and tried to get the data line by line.

public interface EmployeeProjection {

    UUID getEmployeeUuid();

    String getEmployeeName();

    UUID getCompanyUuid();

    String getCompanyName();


    // I use like that
    default String getToString() {
        return "EmployeeName: "   getEmployeeName()   "\n"   
               "CompanyName: "   getCompanyName();
    }
}

Is it a good approach or how can I get multiple values by formatting directly from this projection?

CodePudding user response:

Interface based

For "such use case" Spring-Data documentation shows also "Example 83. An Open Projection" (applied to OP domain):

@Value("#{'EmployeeName: '   target.employeeName   '\nCompanyName: '   target.companyName}")
String getFullName();

Example 84. shows the same "A projection interface using a default method for custom logic" approach.

Example 85. shows, how we can delegate the complete method (passing the projection instance):

@Value("#{@someBean.getFullName(target)}")
String getFullName();

Of course for all three approaches we cannot "signature" the method toString():String (due to syntactical limitations) ;(;(


If we want to override the default toString()/hashCode()/equals() (loosing/discarding the advantages of interface-based projections..), just go with (documented):

Class-based Projections (DTOs)

@lombok.Value
public class EmployeeProjection {

    private final UUID employeeUuid;

    private final String employeeName;

    private final UUID companyUuid;

    private final String companyName;

    @Override 
    public String toString() {
        return String.format(
          "EmployeeName: %s%nCompanyName: %s",
          getEmployeeName(),
          getCompanyName()
        );
    }
}

CodePudding user response:

In Java, interfaces cannot contain methods with a body. Your "Interface abstract methods cannot have body" error is not thrown by the fact you are trying to override the "toString()" method, but rather because your "getToString()" method has a body.

Instead, define the "getToString()" method as:

String getToString();

And then when you implement your EmployeeProjection interface in other classes, you can define the body of the method there.

  • Related