您的位置:首页 > 编程语言 > Java开发

java 获取任意类下面的所有方法,任意类下面所有的get方法和get方法的值,动态调用方法

2015-05-27 13:11 489 查看

       1准备一个 参数是对象的方法

public static void getClassAssert(Object obj, Object ect) {
//第一步
 Method[] sta = obj.getClass().getMethods();
Method[] sto = ect.getClass().getMethods();

 if (sta.length == sto.length) {
int length = sta.length;
for (int i = 0; i < length; i++) {
//第二步 获取类所有方法名字
 String left = sta[i].getName();
String right = sto[i].getName();

 Object je = null;
Object ct = null;
//第三步 获取前三个字母是get 的方法
 if (left.substring(0, 3).equals("get")) {
try {
if (left.equals("getClass")) {
continue;
}
//第四动态调用 方法 返回object
 je = obj.getClass().getMethod(left, new Class[] {})
.invoke(obj, new Object[] {});
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
if (right.substring(0, 3).equals("get")) {
try {
if (right.equals("getClass")) {
continue;
}
ct = obj.getClass().getMethod(right, new Class[] {})
.invoke(obj, new Object[] {});
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
getTest.getAssert(je, ct);
}
} else {
getTest.getAssert(true, false);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java
相关文章推荐