java 迭代所有名称以“get”开头的方法 - 比较对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11224217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over all methods that have name starting with "get" - comparing objects
提问by LucasSeveryn
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.
是否有可能以某种方式迭代对象的每个方法,名称以“get”开头?我想比较两个非常复杂的自定义对象,它们的字段由基于其他自定义对象的数据结构组成。我想要做的是获取每个 get 方法的结果的哈希码,并比较每个字段是否相等。
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()
}
回答by Marko Topolnik
Certainly it's possible, and in fact 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
}
}
回答by madhairsilence
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
}
}