java 内省

Posted 小琪子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

  

以上是关于java 内省的主要内容,如果未能解决你的问题,请参考以下文章

java内省小记

理解Java的反射与内省及其区别

java 中反射机制和内省机制的区别是啥?

java----内省

Java内省详解

java学习之内省