Is it possible to somehow iterate over every method of an object, with name starting with "get"? I want to compare two very complex custom objects, that have fields consisting of data structures based on other custom objects. What I want to do is to get a hashcode of the result of every get method, and compare if they are equal for every field.
Sorry if it is not very understandable, if you have questions please ask. Thanks for any help and suggestions
I thought of something like that:
for(method m : gettersOfMyClass){
boolean same = object1.m.hashCode() == object2.m.hashCode()
}
Yes, it is possible, and in fact it's quite simple:
public static void main(String[] args) throws Exception {
final Object o = "";
for (Method m : o.getClass().getMethods()) {
if (m.getName().startsWith("get") && m.getParameterTypes().length == 0) {
final Object r = m.invoke(o);
// do your thing with r
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With