使用反射调用方法

    今天我一同事有一问题:他有一个po,里面有上百个属性,现在他需要根据用户勾选上的来返显到前台,且以后属性还会增加。

若po中只有几个属性,我们可以只用if/else判断来做这个功能;但在他这里这么写就有点难受了,所以考虑用反射来实现这个功能。

 

1、创建一个Student:

 class  Student{
    String name;
    int age;
    int height;
    int weight;

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

     public int getHeight() {
         return height;
     }

     public void setHeight(int height) {
         this.height = height;
     }

     public int getWeight() {
         return weight;
     }

     public void setWeight(int weight) {
         this.weight = weight;
     }
 }

2、反射类

 private static <T> void getFunctionByClass(T require,String functionName){
       Class re= require.getClass();
       try {
           Field field = re.getDeclaredField(functionName);
           System.out.println("field:"+field);
           System.out.println(field.get(require));//调用对象的方法
       } catch (Exception e) {
           e.printStackTrace();
       } 
   }

3、main函数

public static void  main(String[] args){
        Student a1=new Student();
        a1.setName("Li Ming");
        a1.setAge(18);
        a1.setHeight(180);
        a1.setWeight(90);
        getFunctionByClass(a1,"name");
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值