English 中文(简体)
Generating equals / hashcode / toString using annotation
原标题:

I believe I read somewhere people generating equals / hashcode / toString methods during compile time (using APT) by identifying which fields should be part of the hash / equality test. I couldn t find anything like that on the web (I might have dreamed it ?) ...

That could be done like that :

public class Person {
  @Id @GeneratedValue private Integer id;

  @Identity private String firstName, lastName;
  @Identity private Date dateOfBirth;

  //...
}

For an entity (so we want to exlude some fields, like the id).

Or like a scala case class i.e a value object :

@ValueObject
public class Color {
  private int red, green, blue;
}

Not only the file becomes more readable and easier to write, but it also helps ensuring that all the attributes are part of the equals / hashcode (in case you add another attribute later on, without updating the methods accordingly).

I heard APT isn t very well supported in IDE but I wouldn t see that as a major issue. After all, tests are mainly run by continuous integration servers.

Any idea if this has been done already and if not why ? Thanks

最佳回答

I m using Project Lombok for this.

问题回答

While Pojomatic does not do compile-time bytecode manipulation, it does support easy creation of equals, hashCode and toString methods, using annotations to customize their behavior.

Google s solution in library AutoValue: https://github.com/google/auto/tree/master/value uses @AutoValue annotation + generation of sources before compilation.

Several competing solutions are discussed in the following presentation: https://docs.google.com/presentation/d/14u_h-lMn7f1rXE1nDiLX0azS3IkgjGl5uxp5jGJ75RE/edit





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签