码迷,mamicode.com
首页 > 编程语言 > 详细

java 内省

时间:2016-03-28 10:18:41      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

用内省来操作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

  

java 内省

标签:

原文地址:http://www.cnblogs.com/dbqjava/p/5327966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!