首页 > 其他 > 详细

JAVA内省(Introspector)一

时间:2014-03-03 02:47:14      阅读:453      评论:0      收藏:0      [点我收藏+]

‘?ntr?spekt?

什么是Java内省:内省是Java语言对Bean类属性、事件的一种缺省处理方法。

Java内省的作用:一般在开发框架时,当需要操作一个JavaBean时,如果一直用反射来操作,显得很麻烦;所以sun公司开发一套API专门来用来操作JavaBean

package com.javax.iong.javabean0301;

public class Person {
	
	private String name;
	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;
	}
	private int age;

}

package com.javax.iong.javabean0301;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import org.junit.Test;

public class Test1 {

	@Test
	public void tes1() throws Exception {
		Class<?> cl = Class.forName("com.javax.iong.javabean0301.Person");
		// 在bean上进行内省
		BeanInfo beaninfo = Introspector.getBeanInfo(cl, Object.class);
		PropertyDescriptor[] pro = beaninfo.getPropertyDescriptors();
		Person p = new Person();
		System.out.print("Person的属性有:");
		for (PropertyDescriptor pr : pro) {
			System.out.print(pr.getName() + " ");
		}
		System.out.println("");
		for (PropertyDescriptor pr : pro) {
			// 获取beal的set方法
			Method writeme = pr.getWriteMethod();
			if (pr.getName().equals("name")) {
				// 执行方法
				writeme.invoke(p, "xiong");
			}
			if (pr.getName().equals("age")) {
				writeme.invoke(p, 23);
			}
			// 获取beal的get方法
			Method method = pr.getReadMethod();
			System.out.print(method.invoke(p) + " ");

		}
	}

	@Test
	public void test2() throws Exception {
		PropertyDescriptor pro = new PropertyDescriptor("name", Person.class);
		Person preson=new Person();
		Method  method=pro.getWriteMethod();
		method.invoke(preson, "xiong");
		System.out.println(pro.getReadMethod().invoke(preson));
	}
}



JAVA内省(Introspector)一,布布扣,bubuko.com

JAVA内省(Introspector)一

原文:http://blog.csdn.net/x605940745/article/details/20240959

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!