原文地址:java反射机制,通过类名获取对象,通过方法名和参数调
作者:青凡
try {
//得到对象
Class c = Class. forName(" 完整类名");
Object yourObj = c.newInstance();
//得到方法
Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
}
//获取到方法对象,假设方法的参数是一个int,method名为setAge
Method sAge = c. getMethod("setAge", new Class[] { int.class});
//获得参数Object
Object[] arguments = new Object[] { new Integer(37)};
//执行方法
sAge. invoke( yourObj , arguments);
} catch (Exception e) {
}
//得到对象
Class c = Class. forName(" 完整类名");
Object yourObj = c.newInstance();
//得到方法
Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
}
//获取到方法对象,假设方法的参数是一个int,method名为setAge
Method sAge = c. getMethod("setAge", new Class[] { int.class});
//获得参数Object
Object[] arguments = new Object[] { new Integer(37)};
//执行方法
sAge. invoke( yourObj , arguments);
} catch (Exception e) {
}