JavaBean内省的用法

Introspector (Java Platform SE 6)<!-- Generated by javadoc (build 1.6.0-beta2) on Mon Mar 19 18:21:51 CST 2007 --> <script type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title=&quot;Introspector (Java Platform SE 6)&quot;; } } </script>

<noscript></noscript>

一、本文主要是介绍利用Introspector类,如何查找bean相关属性的,和设置属性的方法?

Introspector 类为通过工具学习有关受目标 Java Bean 支持的属性、事件和方法的知识提供了一个标准方法。

对于这三种信息,Introspector 将分别分析 bean 的类和超类,寻找显式或隐式信息,使用这些信息构建一个全面描述目标 bean 的 BeanInfo 对象。

下面利用代码说明如何用JavaBean的属性利用javaBean内省的功能得到此属性的值?

这个是JavaBean类

package cn.itcast.day1;

import java.util.Date;

public class ReflectPoint {
	private Date birthday = new Date();//注意一定要new一个Date否则会报null异常
	
	private int x;
	public int y;
	public String str1 = "ball";
	public String str2 = "basketball";
	public String str3 = "itcast";
	
	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + x;
		result = prime * result + y;
		return result;
	}


	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final ReflectPoint other = (ReflectPoint) obj;
		if (x != other.x)
			return false;
		if (y != other.y)
			return false;
		return true;
	}


	@Override
	public String toString(){
		return str1 + ":" + str2 + ":" + str3;
	}


	public int getX() {
		return x;
	}


	public void setX(int x) {
		this.x = x;
	}


	public int getY() {
		return y;
	}


	public void setY(int y) {
		this.y = y;
	}


	public Date getBirthday() {
		return birthday;
	}


	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
}

 测试方法类:

getProperty方法,是根据Introspector.getBeanInfo
获取javaBean的所有属性,然后获得的属性与方法传过来的属性字符串遍历判断是否有相等的属性字段名称
如果找到相等的属性字段,就调用方法得到此属性对应的值.
	public class IntroSpectorTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		ReflectPoint pt1 = new ReflectPoint(3,5);
		
		String propertyName = "x";
		//"x"-->"X"-->"getX"-->MethodGetX-->
		Object retVal = getProperty(pt1, propertyName);
		System.out.println(retVal);

               Object value = 7;
		
		setProperties(pt1, propertyName, value);

private static void setProperties(Object pt1, String propertyName,
			Object value) throws IntrospectionException,
			IllegalAccessException, InvocationTargetException {
		PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
		Method methodSetX = pd2.getWriteMethod();
		methodSetX.invoke(pt1,value);
	}
private static Object getProperty(Object pt1, String propertyName)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
        // 这种是简易的方式 
		/*PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
		Method methodGetX = pd.getReadMethod();
		Object retVal = methodGetX.invoke(pt1);*/
                 //下面的方式优点就是如果用户传过来的字符串与javaBean中的属性名称没有一个匹配上的时候,可以用
                 //一个默认的值或者抛出异常
		BeanInfo beanInfo =  Introspector.getBeanInfo(pt1.getClass());
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
		Object retVal = null;
		for(PropertyDescriptor pd : pds){
			if(pd.getName().equals(propertyName))
			{
				Method methodGetX = pd.getReadMethod();
				retVal = methodGetX.invoke(pt1);
				break;
			}
		}
		return retVal;
	}
}

 二、下面介绍commons-beanutils  开源的apache基金的工具包?

         java-beanutils.jar工具包还需要与commons-logging.jar配合使用

   可以利用BeanUtils中的getProperty

System.out.println(BeanUtils.getProperty(pt1, "x"));
		BeanUtils.setProperty(pt1, "x", "9");
		System.out.println(pt1.getX());

 如此简单的代码就可以得到javaBean中属性字段的值,还可以设置javaBean中字段的属性值

但是注意BeanUtil设置值以及得到的属性值是用的字符串操作.............

可以利用代码BeanUtils.getProperty(pt1,"x").getClass().getName();查看得到的属性值是什么类型,因此利用工具包

是有利于以后的web开发,因为传到前台页面都是字符串型

BeanUtil类还可以支持javaBean属性之间的级联设置javaBean,比如RefelectPoint类中的Date  birthday属性,又因为Date类中有一个方法getTime

BeanUtils.setProperty(pt1, "birthday.time", "13");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));

//java7的新特性
        Map map = {name:"zxx",age:18};
        BeanUtils.setProperty(map, "name", "lhm");
        */

PropertyUtils.setProperty(pt1, "x", 9);
        System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());

内容概要:本文介绍了多种开发者工具及其对开发效率的提升作用。首先,介绍了两款集成开发环境(IDE):IntelliJ IDEA 以其智能代码补全、强大的调试工具和项目管理功能适用于Java开发者;VS Code 则凭借轻量级和多种编程语言的插件支持成为前端开发者的常用工具。其次,提到了基于 GPT-4 的智能代码生成工具 Cursor,它通过对话式编程显著提高了开发效率。接着,阐述了版本控制系统 Git 的重要性,包括记录代码修改、分支管理和协作功能。然后,介绍了 Postman 作为 API 全生命周期管理工具,可创建、测试和文档化 API,缩短前后端联调时间。再者,提到 SonarQube 这款代码质量管理工具,能自动扫描代码并检测潜在的质量问题。还介绍了 Docker 容器化工具,通过定义应用的运行环境和依赖,确保环境一致性。最后,提及了线上诊断工具 Arthas 和性能调优工具 JProfiler,分别用于生产环境排障和性能优化。 适合人群:所有希望提高开发效率的程序员,尤其是有一定开发经验的软件工程师和技术团队。 使用场景及目标:①选择合适的 IDE 提升编码速度和代码质量;②利用 AI 编程助手加快开发进程;③通过 Git 实现高效的版本控制和团队协作;④使用 Postman 管理 API 的全生命周期;⑤借助 SonarQube 提高代码质量;⑥采用 Docker 实现环境一致性;⑦运用 Arthas 和 JProfiler 进行线上诊断和性能调优。 阅读建议:根据个人或团队的需求选择适合的工具,深入理解每种工具的功能特点,并在实际开发中不断实践和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值