关于java反射调用class中的方法

来源:互联网 发布:软件创业成功案例 编辑:程序博客网 时间:2024/05/22 16:57

一、参数参数类型要对上

Request target = (Request) object;
Class<?> clazz = target.getClass();
String tmethod = "get"
+ (fieldclass.charAt(0) + "").toUpperCase()
+ fieldclass.substring(1, fieldclass.length());
Method m1;
Object neestr = "";
try {
m1 = clazz.getDeclaredMethod(tmethod);//参数类型
if (null != m1) {
Object inobj = m1.invoke(target);
if (null != inobj) {
neestr = inobj;
}
}


} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}

二、可台使用object作为通用参数,通用所有参数(不能有不同参数类型的重载方法)

Method m1;
m1 = getMethodByName(clazz,tmethod);

--私有方法

private Method getMethodByName(Class<?> clazz, String methodName){
Method rm = null;
if(null == methodName){
return rm;
}
Method methods[] = clazz.getDeclaredMethods();
if(null != methods && methods.length > 0){
for(Method md : methods){
if(methodName.equals(md.getName())){
rm = md;
break;
}
}
}
return rm;
}

0 0