反 射

1、bean

public class User {
	private int id;
	private String name;
	public User(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public User() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

2、reflection

public static void main(String[] args) throws Exception{
		// 类的路径  包名+类名
		String path = "net.ylj.reflection.bean.User";
		//获取class的三种方式
		Class clazz = Class.forName(path);
		Class clazz2 = User.class;
		Class clazz3 = path.getClass();
		
		//类名称
		System.out.println(clazz.getName());		// 包名+类名
		System.out.println(clazz.getSimpleName());	// 类名
		
		//属性
		Field [] public_field = clazz.getFields();	         //public修饰的属性
		Field [] all_field = clazz.getDeclaredFields(); //所有属性
		Field f0 = clazz.getDeclaredField("id");     //获取指定属性
		for(Field f : all_field){  // 或public_field
			System.out.println(f.getType() + " == " + f.getName()); // 类型  名称
		}
		
		//方法
		Method[] public_method = clazz.getMethods(); 	//public修饰的方法
		Method[] all_method = clazz.getDeclaredMethods(); 	//所有方法
		Method method = clazz.getDeclaredMethod("setId",int.class);	//获取指定方法,方法无参数时写 null
		
		//构造方法
		Constructor[] constructor = clazz.getConstructors(); //获取所有构造方法
		Constructor cc = clazz.getDeclaredConstructor(null); //获取无参构造方法
		//反射调用无参构造方法
		User user = (User) clazz.newInstance();
		//反射调用有参构造方法
		Constructor<User> c = clazz.getConstructor(int.class,String.class);
		User u = c.newInstance(12,"小明");
		
		//反射调用普通方法
		Method m = clazz.getDeclaredMethod("setName", String.class);
		m.invoke(u, "小红");	//like u.setName("小红");
		
		//反射,通过属性修改属性值
		Field field = clazz.getDeclaredField("name");
		field.setAccessible(true);	//设置该属性跳过安全检查
		field.set(u, "小刚");	//like u.setName("小刚");
	}

猜你喜欢

转载自1151474146.iteye.com/blog/2368646