java 内省

用内省来操作Bean会给程序带来很大的便利,特别是在很大的实体对象的时候,在其属性很多的时候要为其赋值的时候,

 

package com.bean;

public class User {

	private String uid;
	private String userName;
	private String userPass;
	private String age;
	private String sex;
	
	public User(){}
	
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPass() {
		return userPass;
	}
	public void setUserPass(String userPass) {
		this.userPass = userPass;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public User(String uid, String userName, String userPass, String age,
			String sex) {
		super();
		this.uid = uid;
		this.userName = userName;
		this.userPass = userPass;
		this.age = age;
		this.sex = sex;
	}
	
	@Override
	public String toString() {
		return "User [uid=" + uid + ", userName=" + userName + ", userPass="
				+ userPass + ", age=" + age + ", sex=" + sex + "]";
	}
	
	
}

  

package com.bean;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

public class beanUtils {

	/**
	 * java内省
	 * @param args
	 * @throws IntrospectionException
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 */
	public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		BeanInfo beanInfo = Introspector.getBeanInfo(User.class, Object.class);
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
		User user = new User();
		for(PropertyDescriptor pd : pds){
			System.out.println(pd.getName());
		}
		PropertyDescriptor pd = new PropertyDescriptor("age", User.class);
		pd.getWriteMethod().invoke(user, "22");
		System.out.println(pd.getReadMethod().invoke(user));
		
	}
}

  

age
sex
uid
userName
userPass
22

  

转载于:https://www.cnblogs.com/dbqjava/p/5327966.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值