Java反射机制:
Java程序在JVM运行状态中,对于任意一个类都知道它的所有属性和方法;
并且对于任意一个对象在任意时刻都能调用其任意的一个方法,这种动态
获取类的属性和方法及动态调用方法的功能叫做Java的反射机制。
Java中所有操作皆为对象操作,因此Java程序运行的时候每个类的信息都保存
在class对象中,类的所有信息(包括声明的属性、定义的方法)都存在Class
类中。
获取Class对象的方法:
1.类的.class()方法,每个类中都有该方法,如:User.class()
2.object.getClass(),每个实例化对象中都有该方法,如:new User().getClass()
2.获取构造器
Java程序在JVM运行状态中,对于任意一个类都知道它的所有属性和方法;
并且对于任意一个对象在任意时刻都能调用其任意的一个方法,这种动态
获取类的属性和方法及动态调用方法的功能叫做Java的反射机制。
Java中所有操作皆为对象操作,因此Java程序运行的时候每个类的信息都保存
在class对象中,类的所有信息(包括声明的属性、定义的方法)都存在Class
类中。
获取Class对象的方法:
1.类的.class()方法,每个类中都有该方法,如:User.class()
2.object.getClass(),每个实例化对象中都有该方法,如:new User().getClass()
3.Class.forName(String className),调用Class的静态方法forName获取,参数为给定的字符串的类
代码:
User user = new User();
Class<?> cls = user.getClass();
Class<?> cls = User.class;
Class<?> cls = Class.forName("com.shangpin.reflect.User");
1.获取类声明的属性
public void field(Class<?> cls, User user) throws IllegalArgumentException, Exception{
//获取所有的属性
Field[] fields = cls.getDeclaredFields();
for(Field field : fields){
//属性字段名称
String name = field.getName();
System.out.println("field name:" + name);
//字段类型
Class<?> type = field.getType();
System.out.println("field type:" + type);
//字段的修饰符值private:2,protected:4,public:1
int modifier = field.getModifiers();
System.out.println("field modifier:" + modifier);
//获取属性值
field.setAccessible(true);
Object object = field.get(user);
System.out.println("field value:" + object);
Type type2 = field.getGenericType();
System.out.println("type2========" + type2);
}
//获取声明为公共修饰符的属性,即属性的修饰符为public
Field[] fds = cls.getFields();
for(Field field : fds){
System.out.println("public field name:" + field.getName());
}
}
2.获取构造器
public void constructor(Class<?> cls, User user){
Constructor<?>[] constructors = cls.getConstructors();
for(Constructor<?> constructor : constructors){
//构造器名字
String name = constructor.getName();
System.out.println("constructor name:" + name);
//构造器中形参的类型集合
Type[] types = constructor.getGenericParameterTypes();
for(Type type : types){
//形参类型
System.out.println("constructor params type:" + type);
}
}
}
3.获取方法
public void method(Class<?> cls, User user) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Method[] methods = cls.getMethods();
for(Method method : methods){
//方法名称
String name = method.getName();
System.out.println("method name:" + name);
//方法返回类型
Class<?> type = method.getReturnType();
System.out.println("method type:" + type);
if("print".equals(name)){
method.invoke(user, "zhangsan", null);//调起方法
}
//方法参数类型
Class<?>[] clss = method.getParameterTypes();
for(Class<?> cl : clss){
System.out.println("method param type==" + cl);
}
//方法参数类型
Type[] types = method.getGenericParameterTypes();
for(Type type2 : types){
System.out.println("type:" + type2);
}
}
}