userbean.java_javaBean的内省操作

反射技术实际是已经能够完全满足我们对javaBean的各种操作了,但是为了方便JDK还是为我们提供了一套操纵JavaBean的API,我们称这套API为内省操作(Introspector),下面示范一下通常的两种内省操作.

既然内省是作用于javaBean的,那么我们先提供一个JavaBean类,本例为UserBean.java

package net.csdn.blog;

public class UserBean {

private String name;

private int age;

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;

}

}

方法一:第一种方法为较繁琐的一种方法,但通常在批量操纵javaBean中的方法时很管用。

package net.csdn.blog;

import java.beans.BeanInfo;

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class UserBeanHandlerOne {

public static void main(String args[]) {

UserBean user = new UserBean();

try {

handleBean(user);

} catch (Exception e) {

e.printStackTrace();

}

}

private static void handleBean(UserBean user)

throws IntrospectionException, IllegalArgumentException,

IllegalAccessException, InvocationTargetException {

BeanInfo bi = Introspector.getBeanInfo(user.getClass());

PropertyDescriptor[] pd = bi.getPropertyDescriptors();

for (PropertyDescriptor p : pd) {

String attrName=p.getName();

if(attrName.equals("name")||attrName.equals("age")){

Method writeMethod=p.getWriteMethod();//得到set方法

Class clazz[]=writeMethod.getParameterTypes();

if(clazz[0]==int.class)

writeMethod.invoke(user, 20);

else

writeMethod.invoke(user, "peter");//执行set方法

Method readMethod = p.getReadMethod();//获取get方法

Object obj = readMethod.invoke(user);//执行get方法

System.out.println(obj);

}

}

}

}

方法二:

第二种方法是对于某个特定的属性 package net.csdn.blog;

import java.beans.IntrospectionException;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class UserBeanHandlerTwo {

public static void main(String args[]) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{

UserBean ub=new UserBean();

PropertyDescriptor pd=new PropertyDescriptor("name",UserBean.class);

Method writeMethod=pd.getWriteMethod();

writeMethod.invoke(ub,"peter");

Method readMethod=pd.getReadMethod();

Object str=readMethod.invoke(ub);

System.out.println(str);

}

}

这两种方法均可以用来作为javaBean的内省操作 。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值