java反射浅谈

反射机制概念:JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。

这是一个User实体类:

package com.xuhang.bean;

public class User {
	private Integer id;
    private Integer age;
    private String name;
    
    
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public User(Integer id, Integer age, String name) {
		super();
		this.id = id;
		this.age = age;
		this.name = name;
	}
    

}
反射机制案例代码:
package com.xuhang.rereflect;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import com.xuhang.bean.User;

public class HangReFlectTest2 {
	public static void main(String[] args) throws Exception {
		// 得到类路径
		String path = "com.xuhang.bean.User";
		//根据类路径获取这个类
		Class<User> clazz = (Class<User>) Class.forName(path);
		//实例化该类
		User user = clazz.newInstance();
		//查看这个类是否实例化成功
		System.out.println(user);
		//获取实体类的setName()方法
		Method method = clazz.getDeclaredMethod("setName", String.class);
		//使用invoke反射设置值
		method.invoke(user, "xuhang");
		//通过地段反射获取对应属性
		PropertyDescriptor prop = new PropertyDescriptor("name",User.class);
		//getReadMethod相当于get()方法,这里是通过属性反射获取name字段对应的值
		Object obj = prop.getReadMethod().invoke(user);
		System.out.println(obj);
	}

}

猜你喜欢

转载自blog.csdn.net/XuHang666/article/details/80247619