神秘的 J2ee 殿堂

·古之学者必有师·做学者亦要做师者·FIGHTING·

java反射应用对BEAN的操作,写通用类、标签时有用


package
 com.hunau.liuyong;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

//其中User就是一个bean,里面就一个name属性
public
 class Test {
    
public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
User user
=new User();
List list
=new ArrayList();
list.add(user);
System.out.print(
"+++++++");
Method method
=getSetMethod(list.get(0).getClass(),"name");
System.out.print(
"+++++++");
method.invoke(list.get(
0),"liuyong");
method
=getGetMethod(list.get(0).getClass(),"name");
System.out.println(method.invoke(list.get(
0),null));
}

public static Method getGetMethod(Class objectClass,String fieldName) throws SecurityException, NoSuchMethodException{
    System.out.print(
"+++++++");
    StringBuffer sb
=new StringBuffer();
    sb.append(
"get");
    sb.append(fieldName.substring(
0,1).toUpperCase());
    sb.append(fieldName.substring(
1));
    Method method
=objectClass.getMethod(sb.toString(), null);
    System.out.print(
"+++++++");
    
return method;
}

public static Method getSetMethod(Class objectClass,String fieldName) throws SecurityException, NoSuchMethodException, NoSuchFieldException{
    Class[] parameterTypes
=new Class[1];
    Field field
=objectClass.getDeclaredField(fieldName);
    System.out.println(
"dasg");
    parameterTypes[
0]=field.getType();
    StringBuffer sb
=new StringBuffer();
    System.out.println(
"dasg");
    sb.append(
"set");
    sb.append(fieldName.substring(
0,1).toUpperCase());
    sb.append(fieldName.substring(
1));
    System.out.println(fieldName);
    Method method
=objectClass.getMethod(sb.toString(), parameterTypes);
    System.out.println(
"dasg");
    
return method;
    
}
}

posted on 2008-07-11 13:52 月芽儿 阅读(753) 评论(1)  编辑  收藏 所属分类: J2EE学习心得

评论

# re: java反射应用对BEAN的操作,写通用类、标签时有用 2010-07-30 09:32 钢炮

写点实战性的东西比较好吧!!  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(2)

随笔分类

随笔档案

相册

搜索

最新评论

阅读排行榜

评论排行榜