深入理解J2SE—Introspector(内省)

来源:互联网 发布:tumblr类似的软件 编辑:程序博客网 时间:2024/06/05 03:25

Introspector (内省)是操作javaBean的属性API,用来访问某个属性的 getter/setter 方法。

什么事JavaBean?

1.具备空参构造。

2.提供熟悉的get/set方法。

3.属性对象变量实例化。


例如以下的JAVABEAN中

public class User {private String name;private String password;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
我们可以通过User中的方法get,set来获得值和设置值。在jdk中提供了一套API用来访问某个熟悉的get/set方法。这就是JAVA的内省。


JDK内省类库

propertyDescriptor类

利用propertyDescriptor类,在其实例化的时候传入属性字符串和JAVABean。这样就能构造出一个PropertyDescriptor。利用PropertyDescriptor来获取javaBean的get/set方法。

public class propertyDescriptorTest {public static void main(String[] args) throws Exception {User u = new User();setProperty(u, "name");getProperty(u, "name");}/** * 向指定的属性值中写入值 * @param user * @param propertyName * @throws Exception */public static void setProperty(User user, String propertyName)throws Exception {PropertyDescriptor propertyDescriptor= new PropertyDescriptor(propertyName,User.class);Method methodSetUserName = propertyDescriptor.getWriteMethod();//获取set方法methodSetUserName.invoke(user, "haha"); //调用set方法,并传入参数System.out.println("setName:" + user.getName());}/** * 从指定的属性值中获取值 * @param user * @param propertyName * @throws Exception */public static void getProperty(User user, String propertyName)throws Exception {PropertyDescriptor propertyDescriptor= new PropertyDescriptor(propertyName,User.class);Method methodGetUserName = propertyDescriptor.getReadMethod(); //获取get方法Object name = methodGetUserName.invoke(user);//调用get方法System.out.println("getName:" + name.toString());}}

Introspector类

利用Introspector可以直接获取class的beanInfo.通过beanInfo获取JAVABean中所有的PropertyDescriptor。利用PropertyDescriptor获得get方法或set方法。

public class IntrospectorTest {public static void main(String[] args) throws IntrospectionException,IllegalAccessException, IllegalArgumentException,InvocationTargetException {User user = new User();BeanInfo beanInfo = Introspector.getBeanInfo(User.class);PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();//获取PropertyDescriptor的数组for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {System.out.println(propertyDescriptor.getName());if (propertyDescriptor.getName().equals("name")) {Method writeMethod = propertyDescriptor.getWriteMethod();writeMethod.invoke(user, "haha");}}System.out.println(user.getName());}}

以上是两种JAVA的内省,用于操作javabean的api。但是有没有想过一个问题,既然javabean已经有了get/set方法,为何还有利用内省去操作javabean。这里就涉及到了对java内省的应用。下一次会总结这一部分内容。

0 0
原创粉丝点击