java反射机制

1. 什么是反射
反射java语言中的一种机制,通过这种机制可以动态的实例化对象、读写属性、调用方法

2一切反射相关的代码都从获得类(java.lang.Class)对象开始
2.1 Class.forName(完整类名)

	Class clzz=Class.forName("com.zking.refect.Student");
		System.err.println(clzz);  

结果

class com.zking.refect.Student

  


2.2 类名.class

Class clzz=Student.class;
 System.err.println(clzz);

结果

class com.zking.refect.Student

2.3 对象.getClass()

Student s = new Student();
Class clzz = s.getClass();
System.out.println(clzz);

结果

class com.zking.refect.Student

  

3. 反射三大作用(java.lang.reflect.*)
3.1 实例化对象
c.newInstance()

Constructor.getConstructor/Constructor.getDeclaredConstructor
注:一定要提供无参构造器

Class<Student> clz=Student.class;
	        //反射调用无参构造方法创建学生对象
	        Student stu=(Student) clz.newInstance();
	        System.out.println(stu);

结果

调用无参构造方法创建了一个学生对象

 

3.2 动态调用方法
Method m;
m.invoke

Student stu=new Student();
	Class clz=stu.getClass();
	Method m=clz.getDeclaredMethod("hello");
	m.invoke(stu);

结果

你好!我是null

3.3 读写属性
Field set/get

Student stu=new Student("s002","zs");
Class clz=stu.getClass();
	Field field=clz.getDeclaredField("age");
	field.set(stu, 26);
	System.out.println(stu);
	

  结果

Student [sid=s002, sname=zs, age=26]

  


4. 访问修饰符

获取修饰符之后返回的是int类型,并且是一个常量值,

在java中修饰符有11种(6个常用的和5个不常用的)

常用的修饰符为:public private protected friendly abstract final

不常用的修饰符为: native strictfp synchronizend volatile transiend

Student stu=new Student();
Class clz=stu.getClass();
//获取age的修饰符
Field age=clz.getField("age");
System.out.println(age.getModifiers());

 结果(1代表的修饰符为public)

1

 

	private String sid;

	private String sname;

	public Integer age;
	

  

  

原文地址:https://www.cnblogs.com/xmf3628/p/11024550.html