Is it possible to determine (via Reflection) for a Java Record class, if it has an implicit or explicit definition of equals()
and/or hashCode(Object)
?
For some reflection-based meta-validation of all classes (and thus, also records) across the codebase, we'd like to separate these cases.
As far as I can see, analyzing a record-class through reflection treats both the implicit and explicit as a "declared" method of the concrete type, so I don't see a way to make that distinction.
Sample code (showing there's a declared method in both cases):
public class Test {
public static void main(String[] args) throws Exception {
analyze(R1.class);
analyze(R2.class);
}
private static void analyze(Class<?> clazz) throws Exception {
List<Method> hcMethods = Arrays.stream(clazz.getDeclaredMethods())
.filter(m -> m.getName().equals("hashCode") && m.getParameterTypes().length == 0)
.toList();
System.out.format("Class %s has %s declared hashCode() method(s)\n", clazz.getSimpleName(), hcMethods.size());
}
public record R1() { }
public record R2() {
@Override
public boolean equals(Object obj) {
return obj == this;
}
}
}
Is there a way to still make this separation, in some other way?
Aucun commentaire:
Enregistrer un commentaire