Java 内省机制

1 内省机制的定义

       内省是   Java   语言对   Bean   类属性、事件的一种缺省处理方法。
     例如类 A 中有属性 name, 那我们可以通过 getName,setName 来得到其值或者设置新的值。通过 getName/setName 来访问 name属性,这就是默认的规则。 Java 中提供了一套 API 用来访问某个属性的 getter/setter 方法,通过这些 API 可以使你不需要了解这个规则(但你最好还是要搞清楚),这些 API 存放于包 java.beans中。
     涉及到的几个重要的类:BeanInfo,Introspector,PropertyDescriptor

2 和反射的关系

    内省其实就是用反射来实现的。

3 代码实现

package pkgOne;

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

public class LearnIntrospector {
	public static void printName(Student student)throws Exception {
		PropertyDescriptor descriptor=new PropertyDescriptor("name", Student.class);
		Method getName=descriptor.getReadMethod();
		String name=(String)getName.invoke(student);
		System.out.println("name:"+name);
		
	}
	public static void setName(Student student)throws Exception {
		PropertyDescriptor descriptor=new PropertyDescriptor("name", Student.class);
		Method setName=descriptor.getWriteMethod();
		setName.invoke(student, "newName");
		System.out.println("name:"+student.getName());
	}
	
	public static void printAllProperties(Student student) throws Exception {
		BeanInfo beanInfo=Introspector.getBeanInfo(Student.class);
		PropertyDescriptor[] descriptors=beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor propertyDescriptor : descriptors) {
			Method readMethod=propertyDescriptor.getReadMethod();
			System.out.println(readMethod.invoke(student));
		}
		
	}
	public static void main(String[] args)throws Exception {
		Student llq=new Student(1, "llq", 24);
		printName(llq);
		System.out.println("----------------");
		setName(llq);
		System.out.println("-----------------");
		printAllProperties(llq);
	}
}
运行结果:
name:llq
----------------
name:newName
-----------------
24
class pkgOne.Student
1
newName
invoke getOther method
100


4 应用场景

    Web 开发框架 Struts 中的 FormBean 就是通过内省机制来将表单中的数据映射到类的属性上,因此要求 FormBean 的每个属性要有 getter/setter 方法。但也并不总是这样,什么意思呢?就是说对一个 Bean 类来讲,我可以没有属性,但是只要有 getter/setter 方法中的其中一个,那么 Java 的内省机制就会认为存在一个属性,比如类中有方法 setMobile ,那么就认为存在一个 mobile 的属性,这样可以方便我们把 Bean 类通过一个接口来定义而不用去关心具体实现,不用去关心 Bean中数据的存储。(参考自:http://geeksun.iteye.com/blog/539222


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值