Uso de reflexão

Nome do método Descrição
public String getName () Pegue o nome completo da turma
public Package getPackage () Obtenha informações do pacote
public Class <? super T> getSuperclass () Obtenha ⽗ Class
public Class <?> [] getInterfaces () Obtenha a implementação ⽗ Conecte
public Field [] getFields () Obtenha informações de campo
public Method [] getMethods () Obtenção de informações do método
Construtor público <?> [] getConstructors () Obtenha o método de estrutura
public T newInstance () Reflexão para criar um objeto
public class Test {
    
    
	public static void main(String[] args) throws Exception{
    
    
		print2();
	}
	public static void print2() throws Exception {
    
    
		//类对象
		Class<?> forName = Class.forName("week4.Student");
		//简便方法创建对象
		Student student =(Student) forName.newInstance();
		//复杂方式创建对象
		//通过构造来创建对象
		Constructor<?> constructor = forName.getConstructor();
		Student student1 =(Student) constructor.newInstance();
		System.out.println("------");
		//通过类对象来调用方法
		Method method = forName.getMethod("show", String.class);
		method.invoke(student1, "调用有参方法+小敏");
		//调用无参方法            
		Method method2 = forName.getMethod("print");
		method2.invoke(student1, null);
		//调用toString方法
		Method method3 = forName.getMethod("toString");
		Object invoke = method3.invoke(student1);
		System.out.println(invoke);
		//调用有参构造
		Constructor<?> constructor2 = forName.getConstructor(String.class,int.class);
		//通过构造赋值
		Student stu =(Student) constructor2.newInstance("张三",12);
		System.out.println(stu);
		//调用静态方法
		Method method4 = forName.getMethod("print1");
		method4.invoke(null);
		//调用私有方法
		Method method5 = forName.getDeclaredMethod("privateMethod");
		//java.lang.IllegalAccessException: Class week4.Test can not access 
		//a member of class week4.Student with modifiers "private"
		//抛出该异常。因为是私有方法
		//解决方案:
		method5.setAccessible(true);
		method5.invoke(student);
		//反射获取私有属性
		Field field = forName.getDeclaredField("name");
		field.setAccessible(true);
		field.set(student, "张三");
		System.out.println(field.get(student));
		//反射获取公开属性
		Field field2 = forName.getField("name");
		field2.set(student1, "李四");
		System.out.println(field2.get(student1));
	}
}

Resultados de:

--------我是无参构造
--------我是无参构造
------
调用有参方法+小敏
print
Student [name=null, age=0]
Student [name=张三, age=12]
静态print1
私有privateMethod
张三
李四

Resumindo:

类的对象:基于某个类 new 出来的对象,也称为实例对象。

类对象:类加载的产物,封装了⼀个类的所有信息(类名、⽗类、接⼝、属性、⽅法、构造⽅法) 。
 
注意:每个类加载到内存都会⽣成⼀个唯⼀的类对象

构建类对象有三种方式:
1.通过类的对象,获取类对象
2.通过类名获取类对象
3.通过静态⽅法获取类对象

构建反射对象有两种方式: 
1.通过类对象直接创建
2.通过构造方式创建对象

反射通⽤操作:使⽤反射机制获取类对象,并使⽤Class对象的⽅法获取表示类成员的各种对象(⽐如Constructor、Method、Field 等),实现反射各种应⽤。

私有:
getDeclaredMethods() 获取类中的所有⽅法,包括私有、默认、保护的 、不包含继承的方法
getDeclaredFields()获取所有的属性,包括私有,默认 ,包
都需要设置访问权限将其设置成⽆效(方法名,属性名).setAccessible(true);

Acho que você gosta

Origin blog.csdn.net/weixin_45627031/article/details/110765726
Recomendado
Clasificación