源码请见共享目录CSDN/JavaSE基础/1. InvokeDemo.zip
一、目标
- 读取类的属性;
- 读取方法的信息;
- 调用、修改指定属性的值;
- 调用指定的方法;
二、读取方法、属性信息
package Method;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class InvokerUtil {
public static void printMethodInfo(Class<?> c){
//获取所有的public方法
Method ms[] = c.getMethods();
for (Method method : ms) {
System.out.print(method.getReturnType()+" "+method.getName()+" (");
Class<?>[] params = method.getParameterTypes();
for (Class<?> class1 : params) {
System.out.print(class1.getSimpleName()+",");
}
System.out.println(")");
}
}
public static void printAttributeInfo(Class<?> c){
//获取所有声明的属性
Field []fileds = c.getDeclaredFields();
for (Field field : fileds) {
System.out.println(field.getName()+":"+field.getType());
}
}
}
三、读取、修改属性的值
public class Invoker {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Class<?> c = Foo.class;
Object obj = c.newInstance();
//获取属性,更改属性
Field [] fields = c.getDeclaredFields();
for (Field field : fields) {
//设置属性可见
field.setAccessible(true);
//获取属性名、值
System.out.println(field.getName()+"="+field.get(obj));
//设置属性的值
if(field.getType().equals(int.class)){
field.set(obj, 10);
}else if(field.getType().equals(String.class)){
field.set(obj, "#10");
}
System.out.println(field.getName()+"="+field.get(obj));
//设置属性不可见
field.setAccessible(false);
}
}
}
四、读取、调用方法
package OperateMethod;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import Bean.Foo;
public class Invoker {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
Class<?> c = Foo.class;
Object obj = c.newInstance();
Method m = c.getMethod("test");
m.invoke(obj);
Method m2 = c.getMethod("test1", new Class[]{String.class,String.class});
//通过反射调用obj的m2方法
m2.invoke(obj, new String[]{"12","sfd"});
}
}
五、总结
java.lang.Class类中的方法要了解熟悉,如:
getDeclaredFields获取所有声明的属性;getField获取public修饰的属性;
getDeclaredMethods与getMethods也类似;