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

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;
    
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值