对javaBean简单的内省操作

前言:本博客内容由张孝祥Java高新技术整理而来


首先是一个javaBean


Stundent


package com.dao.chu.movie;

public class Student {

	private int id;
	
	private String name;
	
	private int age;

	public Student() {
	}

	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	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;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
}


然后是内省操作的测试类,这里面有两个自定义的方法,用来设置属性和获得属性。


IntroSpectorTest

package com.dao.chu.movie;

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

public class IntroSpectorTest {

	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
		
		Student student = new Student();
		setProerties(student,"name","张三");
		Object name = getproperties(student, "name");
		System.out.println(name);
	}
	
	/**
	* <p>Title: setProerties</p>
	* <p>Description: 设置javabean属性通用方法</p>
	* @param t
	* @param beanName
	* @param setValue
	* @throws IntrospectionException
	* @throws IllegalAccessException
	* @throws IllegalArgumentException
	* @throws InvocationTargetException
	 */
	private static <T> void setProerties(T t, String beanName,
			String setValue) throws IntrospectionException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		Method setnameMethod = new PropertyDescriptor(beanName, t.getClass()).getWriteMethod();
		setnameMethod.invoke(t,setValue);
	}

	/**
	* <p>Description:获取javabean属性通用方法</p>
	* @param t
	* @param beanName
	* @return
	* @throws IllegalAccessException
	* @throws IllegalArgumentException
	* @throws InvocationTargetException
	* @throws IntrospectionException
	 */
	private static <T> Object getproperties(T t,String beanName)
			throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, IntrospectionException {
		Object nameValue = new PropertyDescriptor(beanName, t.getClass()).getReadMethod().invoke(t);
		return nameValue;
	}
}




输出结果:

张三






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值