public Object myInvoke(String className, String methodName, Object args[]) {
Object results = null;
try {
Class clazz = Class.forName(className);
Method method = null;
for (int i = 0; i < clazz.getMethods().length; i++) {
method = clazz.getMethods()[i];
if(methodName.equals(method.getName())) {
results = method.invoke(clazz.newInstance(), args);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return results;
}
反射常用的几种方法(前面是返回类型后面是方法名)
获取构造函数
1.Constractor getConstrator(Class[] parameterTypes);
2.Constrator[] getConstators();
获取方法
1,Method getMethod(String name, Class[] parameterTypes)
2.Method[] getMethods();
获取属性
1.Filed getFiled(String name);
2.Fileds getFileds();
检查特性
1.Class[] getInterfaces() 、Package getPackage() 、boolean isArray() 、boolean isInterface()
--------------------------------------------------------------------------------------------------------------------
自省机制是使用Introspector实现的。
Introspector的方法大部分都是静态的,可以直接调用,如getBeanInfo(Class beanClass) 可以得到一个JavaBean的BeanInfo实例。
BeanInfo实例包含了一个JavaBean类属性和方法的信息。如:
BeanDescriptor getBeanDescriptor()
MethodDescriptor[] getMethodDescriptors()
PropertyDescriptor[] getPropertyDescriptors()
PropertyDescriptor 代表了属性,可以通过它得到属性的getter方法和setter方法。即:
Method getReadMethod()
Method getWriteMethod()