I am wondering whether it is possible to add something like Objects.equals() that allows runtime checking of types.
Note: I know, that is not what you always want to do, but I think it has its use cases. At least for me.
Example problem: I have some class, let's say, an id of type Integer. And I have an entity Foo with foo.getId()
returns a type Integer. For some reasons I check for equality with Objects.equals(someId, foo.getId())
.
Now I refactor my entity, foo.getId()
will no longer return an Integer but will return Long. Unfortunatelly, there will be no compile time hint at all that Objects.equals(someId, foo.getId())
will never return true. (Yes, stuff like sonarqube helps you a bit).
To solve that, I thought I write something like
private static <T> boolean equals(T object1, T object2) {
return Objects.equals(object1, object2);
}
which.....just does not work. It still accepts any arbitrary Object. Is there any possible solution in Java for this?
Edit: Please note, this question has nothing to do with equals and hashCode of an object or overriding equals of an object in general, I am looking for a compile-time solution.