zoukankan      html  css  js  c++  java
  • Java 遍历一个对象的属性 将非空属性赋值给另一个对象


    //将origin属性注入到destination中 public <T> void mergeObject(T origin, T destination) { if (origin == null || destination == null) return; if (!origin.getClass().equals(destination.getClass())) return; Field[] fields = origin.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true); Object value = fields[i].get(origin); if (null != value) { fields[i].set(destination, value); } fields[i].setAccessible(false); } catch (Exception e) { } } }

      以上是赋值给同类对象,下面是赋值给非同类的对象的同名属性例子

    package test.test;
    
    import java.lang.reflect.Field;
    
    class Temp{
        String a = null;
        String b = null;
        String c = null;
    }
    
    class Temp2{
        String a = null;
    }
    
    public class Test3 {
    
        public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
            // TODO Auto-generated method stub
            Temp t1 = new Temp();
            t1.a ="value a";
            Temp t2 = new Temp();
            t2.b = "value b";
            Temp2 t3 = new Temp2();
            
            Field[] fields = t1.getClass().getDeclaredFields();
            
            
            Field[] fields2 = t3.getClass().getDeclaredFields();
            for(int i=0;i<fields.length;i++)
                if(fields[i].getName().equals(fields2[0].getName())){
                    fields2[0].set(t3, fields[i].get(t1));
                }
            System.out.println(t3.a);
    
        }
    
    }
  • 相关阅读:
    重载小于号
    无聊的会议
    程序内存和时间
    对拍
    读入和输出优化
    codevs 3269 混合背包
    清北第三套题
    codevs 2188 最长上升子序列
    清北第二套题
    [COGS896] 圈奶牛
  • 原文地址:https://www.cnblogs.com/flying607/p/3549837.html
Copyright © 2011-2022 走看看