zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java中的反射

2023-06-13 09:13:13 时间

1.什么是反射? 反射是一种机制,利用反射机制动态的实例化对象、读写属性、调用方法、构造函数。

(以下的文件图片是我自己对反射功能所创建的类)

代码案例如下:

Hello类:

package com.zking.reflect.entity;

import java.io.Serializable;

public class Hello implements Serializable {

		private String name;


		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
		
		
}

 Student类:

package com.zking.reflect.entity;

public class Student {
	private String sid;

	private String sname;

	public Integer age;
	
	String sex;

	public Student() {
		super();
		System.out.println("调用无参构造方法创建了一个学生对象");
	}

	public Student(String sid) {
		super();
		this.sid = sid;
		System.out.println("调用带一个参数的构造方法创建了一个学生对象");
	}

	public Student(String sid, String sname) {
		super();
		this.sid = sid;
		this.sname = sname;
		System.out.println("调用带二个参数的构造方法创建了一个学生对象");
	}

	@SuppressWarnings("unused")
	private Student(Integer age) {
		System.out.println("调用Student类私有的构造方法创建一个学生对象");
		this.age = age;
	}

	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public void hello() {
		System.out.println("你好!我是" + this.sname);
	}

	public void hello(String name) {
		System.out.println(name + "你好!我是" + this.sname);
	}

	@SuppressWarnings("unused")
	private Integer add(Integer a, Integer b) {
		return new Integer(a.intValue() + b.intValue());
	}
}

 Demo1类:

package com.zking.reflect.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.zking.reflect.entity.Hello;
import com.zking.reflect.entity.Student;

public class Demo1 {

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
		//1.什么是反射
		//反射是一种机制,利用反射机制可以动态的实例化对象、读和属性、调用方法及构造函数
		
		//异常
		//1)ClassNotFoundException:类没有发现异常
		//2)InstantiationException:反射实例化异常
		//3)NoSuchFieldException:没有匹配的属性异常
		//4)NoSuchMethodException:没有匹配的方法异常
		//5)IllegalAccessException:没有访问权限异常
		//6)IllegalArgumentException:
		//2.传统实例化方式与反射方式的区别?
		//传统方式
		Hello hello=new Hello();
		System.out.println(hello);
		//反射方式
//		Class cls = Class.forName("com.zking.relfect.entity.Hello");
//		Object hel=cls.newInstance();
		//3.一切与反射相关的操作都从获取类对象开始(3种)
		//1)类名.class
		/*Class cls=Hello.class;
		System.out.println("获取类的全路径名:"+cls.getName());
		System.out.println("获取简单类名:"+cls.getSimpleName());
		System.out.println("获取访问修饰符:"+cls.getModifiers());
		System.out.println("获取包名:"+cls.getPackage());*/
		//2)实例化对象名.getClass()
		//com.zking.relfect.entity.Hello
		//3)Class.forName(类的全路径名/权限定名)
		/*Class cls = Class.forName("com.zking.relfect.entity.Hello");
		System.out.println("获取类的全路径名:"+cls.getName());
		System.out.println("获取简单类名:"+cls.getSimpleName());
		System.out.println("获取访问修饰符:"+cls.getModifiers());
		System.out.println("获取包名:"+cls.getPackage());*/
		
		//获取类对象
		Class cls=Student.class;
		//反射机制实例化对象
		Student stu=(Student) cls.newInstance();
		//4.读写属性(Field)
		//1)获取单个公共的属性
		/*Field field = cls.getField("");
		System.out.println("获取属性名:"+field.getName());
		System.out.println("获取属性的访问修饰符:"+field.getModifiers());
		System.out.println("获取属性类型:"+field.getType());*/
		//2)获取单个公共的、私有的、受保护的、最终的等等属性
		//Field field = cls.getDeclaredField("sex");
		//3)获取所有公共的属性
		/*Field[] fileds=cls.getFields();
		for (Field field : fileds) {
			System.out.println("-------");
			System.out.println("获取属性名:"+field.getName());
			System.out.println("获取属性的访问修饰符:"+field.getModifiers());
			System.out.println("获取属性类型:"+field.getType());
		}*/
		//4)获取所有公共的、私有的、受保护的、最终的等等属性
		/*Field fields[]=cls.getDeclaredFields();
		for (Field field : fields) {
			System.out.println("-------");
			System.out.println("获取属性名:"+field.getName());
			System.out.println("获取属性的访问修饰符:"+field.getModifiers());
			System.out.println("获取属性类型:"+field.getType());
		}*/
		//5)赋值
		//Field field=cls.getField("age");
		/*Field field = cls.getDeclaredField("sid");
		//权限设置
		field.setAccessible(true);
		//参数1:实例化对象
		//参数2:赋值的值
		field.set(stu,"P116");
//		field.set(stu,20);
		//6)取值
		//参数:实例化对象名
		Object obj=field.get(stu);
		System.out.println(obj);*/
		
		//6.调用方法以及构造函数(Method)
		//有参有返回值、无参有返回值、有参无返回值、无参无返回值
		//1)获取单个公共的方法
		/*Method method=cls.getMethod("hello", null);
		System.out.println("获取方法名:"+method.getName());
		System.out.println("获取访问修饰符:"+method.getModifiers());
		System.out.println("获取参数数量:"+method.getParameterCount());
		System.out.println("获取返回类型:"+method.getReturnType());*/
		
		//2)获取单个的公共的、私有的、受保护的、最终的等等
		//Method method=cls.getDeclaredMethod("add", Integer.class,Integer.class);
		//3)获取公共的方法
		/*Method[] methods =  cls.getMethods();
		for (Method method : methods) {
			System.out.println("------");
			System.out.println("获取方法名:"+method.getName());
			System.out.println("获取访问修饰符:"+method.getModifiers());
			System.out.println("获取参数数量:"+method.getParameterCount());
			System.out.println("获取返回类型:"+method.getReturnType());
		}*/
		//4)获取多个的公共的、私有的、受保护的、最终的等等方法
	/*	Method[] methods=cls.getDeclaredMethods();
		for (Method method : methods) {
			System.out.println("------");
			System.out.println("获取方法名:"+method.getName());
			System.out.println("获取访问修饰符:"+method.getModifiers());
			System.out.println("获取参数数量:"+method.getParameterCount());
			System.out.println("获取返回类型:"+method.getReturnType());
		}*/
		
		//5)调用方法
		//Method method=cls.getMethod("hello", String.class);
		
		
		/*Method method=cls.getDeclaredMethod("add", Integer.class,Integer.class);
		//设置权限
		method.setAccessible(true);
		//执行方法
		Object returnValue= method.invoke(stu, 10,20);
		System.out.println(returnValue);*/
	
		//6)调用构造函数
//		Constructor cons=cls.getConstructor(null);
//		cons.newInstance(null);
		
		/*Constructor cons=cls.getConstructor(String.class,String.class);
		cons.newInstance("p116","啦啦");*/
		
		Constructor cons=cls.getDeclaredConstructor(Integer.class);
		cons.setAccessible(true);
		cons.newInstance(60);
		
		
	}
}

2.如何得到类对象    一切反射相关的代码都从获得类对象开始    3种获取方式:      2.1 类名.class;      2.2 对象名.getClass();      2.3 Class.forName(全限定名/全路径名)

3.根据类得到类名(全限定名/全路径名)     1)cName.getName();            -->获取全限定名     2)cName.getSimpleName();         -->获取类名     3)cName.getPackage();             -->获取包名    Field field=cla.getField(“属性名”);

4.根据类得到类的属性

 field.getName();            -->获取属性名             filed.getType();            -->获取属性类型          field.getModifiers();            -->获取属性访问修饰符      field.set(Object,Object);         -->设置属性值,参数1:要设置属性所在对象;参数2:要设置的值;      field.get(Object);            -->获取属性值,参数:要获取属性值的对象                  field.getDeclaredField(“属性名”);    -->获取单个属性(私有、公有、受保护、默认、静态)      field.getDeclaredFields();        -->获取所有属性(私有、公有、受保护、默认、静态)

5.根据类得到类的方法

 //无参无返回、无参有参会、有参无返回、有参有返回  cla.getMethod();            -->获取单个公有方法 cla.getDeclaredMethod();        -->获取当个方法(包括私有、受保护、默认、公有)  cla.getMethods();            -->获取所有公有方法  cla.getDeclaredMethods();        -->获取所有的方法(包括私有、受保护、默认、公有)

 6.根据类得到类的构造方法

 cla.getConstrutor();            -->获取单个公有构造方法 cla.getDeclaredConstrutor();        -->获取单个构造方法(包括私有、受保护、默认、公有)  cla.getConstrutors();            -->获取所有的公有构造方法  cla.getDeclaredConstrutors();        -->获取所有的构造方法(包括私有、受保护、默认、公有)

7.根据类得到类的实现接口列表    Class[] interface=cla.getInterfaces();    -->获取类对象中所有实现接口列表

2~6可以算是总结,大家可以先看看总结,然后在看代码案例

 今天的分享就到这里啦!

下一篇为JSP自定义标签!!