反射的学习(一)----------反射的本质:动态获取类结构,动态调用类成员(创建影子对象)

Class类

Class类指正在运行的Java应用程序中的接口
使用java提供的反射机制可以获取某个类的Class对象,这个Class对象可以调用类的属性和方法,它就相当于这个类的影子。

创建Class对象的三种方法

①使用getClass():先创建对象后调用方法
Object str=new Object();
Class c=str.getClass();
②使用.class属性:无需创建对象,但类型必须可用
Class c=Object.class;
③使用Class类的forName方法:无需创建对象,不考虑类是否存在
Class c=Class.forName(“java.lang.Object”);

获取构造方法

将返回Constructor类型的对象或数组

如何获取Constructor对象
①获取所有公有构造方法:class.getConstructors()
②获取指定的公有构造方法:class.getConstructor(构造参数)
③获取所有构造方法:class.getDeclaredConstructors()
④获取指定的构造方法:class.getDeclaredConstructor(构造参数)

Constructor构造对象

获取到构造方法后,利用其创建Class对象,即它的影子对象
使用 public T(返回泛型) newlnstance(构造参数)
例:Object obj=(Object)constructor.newlnstance(“参数1”,”参数2”);

与构造对象有关的反射方法

①获取构造方法的修饰符:getModifiers();
②获取构造方法的名字:getName();
③获取构造方法的参数类型:getParameterTypes();

实例

  • 先创建一个Person类
public class Person {
	public int id=10;
	public String name="XXX";
	private double price=-1.1;
	
	public Person() {//无参构造函数
		super();
	}

	public Person(int id) {//有参构造函数
		super();
		this.id = id;
	}


	private Person(int id, String name, double price) {//私有构造方法
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	
	//toString()方法
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", price=" + price + "]";
	}
	
	public void add(int a,int b) {
		System.out.println("a+b="+(a+b));
	}
	
}
```javascript
- 实例
```javascript
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class Demo {

	public static void main(String[] args) {
		try {
			Class c=Class.forName("Person");//创建Class对象,Person类与本类在一个包下可直接写入
			//获取构造方法
			Constructor cons[]=c.getDeclaredConstructors();//获取所有构造方法
			//遍历Constructor类型的数组
			for(Constructor con:cons) {
				System.out.print(Modifier.toString(con.getModifiers())+" ");//获取修饰符
				System.out.print(con.getName()+"(");//方法名
				Class paras[]=con.getParameterTypes();//方法参数
				//遍历Class类型数组
				for(int i=0;i<paras.length;i++) {
					System.out.print(paras[i].getSimpleName()+" args");
					if(i!=paras.length-1) {
						System.out.print(",");
					}
				}
				System.out.println("){ }");	
			}
			
			Constructor cs1=c.getDeclaredConstructor();//获取无参数构造方法
			//获取到构造方法后,利用其创建Class对象,即它的影子对象
			Object obj=cs1.newInstance();
			System.out.println(obj.toString());
			
			Constructor cs2=c.getDeclaredConstructor(int.class);//获取有参构造方法
			obj=cs2.newInstance(123);
			System.out.println(obj.toString());
			
			Constructor cs3=c.getDeclaredConstructor(int.class,String.class,double.class);//获取私有有参构造方法
			cs3.setAccessible(true);//获取操作权限
			obj=cs3.newInstance(123,"反射",1.56);
			System.out.println(obj.toString());
			
		} catch (ClassNotFoundException | NoSuchMethodException | SecurityException 
				| InstantiationException | IllegalAccessException | IllegalArgumentException | 
				InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}

  • 运行结果

访问构造方法(运行结果)

获取成员变量

返回Filed类型的对象或数组

如何获取Filed对象
①获取所有公有成员变量:class.getFields();
②获取指定的公有成员变量:class.getField(变量名称);
③获取所有成员变量:class.getDeclaredFields();
④获取指定的成员变量:class.getDeclaredField(变量名称);

成员变量对象获取和修改成员变量的值

get(已经实例化的反射对象):获取成员变量的值
set(已经实例化的反射对象,数值)方法:修改成员变量的值

与成员变量有关的反射方法

①获取成员变量的修饰符:getModifiers();
②获取成员变量的名字:getName();
③获取成员变量的声明类型:getType();

实例

  • 先创建一个Person类
public class Person {
	public int id=10;
	public String name="XXX";
	private double price=-1.1;
	
	public Person() {//无参构造函数
		super();
	}

	public Person(int id) {//有参构造函数
		super();
		this.id = id;
	}


	private Person(int id, String name, double price) {//私有构造方法
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	
	//toString()方法
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", price=" + price + "]";
	}
	
	public void add(int a,int b) {
		System.out.println("a+b="+(a+b));
	}
	
}
  • 实例
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class Demo1 {

	public static void main(String[] args) throws IllegalAccessException {
		try {
			Class c=Class.forName("Person");//创建Class对象,Person类与本类在一个包下可直接写入
			Field f[]=c.getDeclaredFields();//返回所有属性
			//遍历Field类型的数组
			for (Field field : f) {
				System.out.print(Modifier.toString(field.getModifiers())+" ");//获取修饰符
				System.out.print(field.getType().getSimpleName()+" ");//获取声明类型
				System.out.print(field.getName());//获取名字
				System.out.println();
			}
			System.out.println("------------");
			Constructor cs1=c.getDeclaredConstructor();//获取无参数构造方法
			Person e=(Person)cs1.newInstance();//创建已经实例化的反射对象
			Field fs=c.getDeclaredField("name");//获取指定的成员变量
			System.out.println(fs.getName()+"的值为:"+fs.get(e));//获取公有成员变量的值
			
			Field fs1=c.getDeclaredField("price");//获取指定的成员变量
			fs1.setAccessible(true);//获取操作权限
			System.out.println(fs1.getName()+"的值为:"+fs1.get(e));//获取私有成员变量的值
			
			fs.set(e, "zr");//修改成员变量的值
			System.out.println(fs.getName()+"修改后的值:"+fs.get(e));
			fs1.set(e, 3.14);
			System.out.println(fs1.getName()+"修改后的值:"+fs1.get(e));
			
			
		} catch (ClassNotFoundException | SecurityException | IllegalArgumentException | NoSuchFieldException | NoSuchMethodException | InstantiationException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}
  • 运行结果
    访问成员变量(运行结果)

获取成员方法

返回Method类型的对象或数组

如何获取Method对象
①获取所有公有成员方法:class.getMethods();
②获取指定的公有成员方法:class.getMethod(方法名,方法参数);
③获取所有成员方法:class.getDeclaredMethods();
④获取指定的成员方法:class.getDeclaredMethod(方法名,方法参数);

调用成员方法

public Object invoke(调用方法的对象,方法参数);

与成员方法有关的反射方法

①获取成员方法的修饰符:getModifiers();
②获取成员方法的名字:getName();
③获取成员方法的返回类型:getReturnType();
④获取成员方法的参数类型:getParameterTypes();

实例

  • 先创建一个Person类
public class Person {
	public int id=10;
	public String name="XXX";
	private double price=-1.1;
	
	public Person() {//无参构造函数
		super();
	}

	public Person(int id) {//有参构造函数
		super();
		this.id = id;
	}


	private Person(int id, String name, double price) {//私有构造方法
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	
	//toString()方法
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", price=" + price + "]";
	}
	
	public void add(int a,int b) {
		System.out.println("a+b="+(a+b));
	}
	
}
  • 实例
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Demo2 {

	public static void main(String[] args) {
		try {
			Class c=Class.forName("Person");
			Method ms[]=c.getDeclaredMethods();//获取所有成员方法
			for (Method m : ms) {
				System.out.print(Modifier.toString(m.getModifiers())+" ");//获取修饰符
				System.out.print(m.getReturnType().getSimpleName()+" ");//返回值
				System.out.print(m.getName()+"(");//方法名
				Class paras[]=m.getParameterTypes();//方法参数
				//遍历Class类型数组
				for(int i=0;i<paras.length;i++) {
					System.out.print(paras[i].getSimpleName()+" args");
					if(i!=paras.length-1) {
						System.out.print(",");
					}
				}
				System.out.println("){ }");	
			}
			System.out.println("---------");
			
			//调用方法
			Constructor cs=c.getConstructor();
			Object obj=cs.newInstance();//创建已经实例化的反射对象
			Method m=c.getDeclaredMethod("add", int.class,int.class);//获取指定的成员方法
			m.invoke(obj, 1,2);//调用成员方法	
		} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

}

  • 运行结果
    访问成员方法(运行结果)

个人主页

个人主页[link]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值