Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over all methods that have name starting with "get" - comparing objects

Tags:

java

compare

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() 
} 
like image 307
LucasSeveryn Avatar asked Jun 27 '12 10:06

LucasSeveryn


1 Answers

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
    }
  }
}
like image 160
Marko Topolnik Avatar answered Sep 24 '22 13:09

Marko Topolnik