反射-新手必看

大家好,这篇文章主要是针对刚开始接触反射的小伙伴们

什么是反射

Java反射说的是在运行状态中,对于任何一个类,我们都能够知道这个类有哪些方法和属性。对于任何一个对象,我们都能够对它的方法和属性进行调用。我们把这种动态获取对象信息和调用对象方法的功能称之为反射机制。

反射的API Class,Construction,Field,Method

Class:获取一个类对应的Class类的方法

三种方式可以获得:(Class.froName在我们的开发中会比较常用)
		1:类名.class;
		2:对象.getClass();
		3:Class.forName("包名.类名");
		  forName方法用于加载类字节码到内存中,并封装成一个Class对象
		 

Constructor:获得类的构造方法

无参:类名.getConstructor();
有参:类名.getConstructor(参数);

Field:代表某个类中的一个成员变量,并提供动态的访问权限

Field的获得

1:得到所有的Field对象
		Field []fields=对象.getFields();
		Field[]fields=对象.getDeclaredField();
		//getDeclaredFiled 仅能获取类本身的属性成员(包括私有、共有、保护) ,比较常用
		//getField 仅能获取类(及其父类可以自己测试) public属性成员
		2:得到指定的成员变量
		Field name-类名.getField(“name”);
		Field name=类名.getDecalredField("name");

设置Filed变量是否可以访问
		field.setAccessible(boolean);//true  or false
Field变量值的读取、设置
		field.get(Object obj);
		field.set(Object obj,value);

Method:代表某个类中的一个成员方法

Method对象的获得
	1:获得所有的方法
		类名.getDeclaredMethods()
		类名.getMethods()
	2:获得指定的方法
		类名.getDeclaredMethod(String name, Class <?> .. parameterTypes)
		类名.getMethod(String name, Class <?> .. parameterTypes)
	3:通过反射执行方法
		invoke(Object obj,Object...args)	
			//例如现在Person 类中有eat()方法,sleep私有方法,see(String name)带参数方法
			//获得eat方法
			Class classz=Class.forName("Person");
			Person person=(Person)classz.newInstance();
			Method method=classz.getMethod("eat");
			method.setAccessible(true);
			method.invoke(person);
			//获得sleep方法
```			Class classz=Class.forName("Person");
			Person person=(Person)classz.newInstance();
			Method method=classz.getDeclaredMethod("sleep");
			method.setAccessible(true);
			method.invoke(person, null);
			//获得see方法
```			Class classz=Class.forName("Person");
			Person person=(Person)classz.newInstance();
			Method method=classz.getDeclaredMethod("see",String.class);
			method.setAccessible(true);
			Object obj = method.invoke(person, "Lasy");

看到这里你应该对反射有了一个简单的了解了,其实我们平时写代码用的是比较少的反射技术,但是在一些主流框架中反射技术的应用是比较多的,所以大家一定要掌握好反射技术哦

发布了24 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44519467/article/details/103242786