13

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() 
} 
4

2 に答える 2

27

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
    }
  }
}
于 2012-06-27T10:38:00.163 に答える
1

Looks like some thing to deal with reflex concept. Reverse engineering the Object

May be this is what you need

Sample Class :

class Syndrome{
public void getMethod1(){}
public void getMethod2(){}
public void getMethod3(){}
public void getMethod4(){}
}

Main Method:

Syndrome syndrome = new Syndrome();

Method[] methods = syndrome.getClass().getMethods();

for( int index =0; index < methods.length; index++){

if( methods[index].getName().contains( "get")){
    // Do something here
}

}
于 2012-06-27T10:41:02.033 に答える