栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

反射 | 运用反射比较两个对象的属性是否相同

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

反射 | 运用反射比较两个对象的属性是否相同

先定义一个实体类Fruit

package reflection;

public class Fruit {

    private String name;

    private Integer price;

    private String branch;

    private Integer count;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }
}

使用反射比较两个不同对象的属性值是否相同

package reflection;

import java.lang.reflect.Field;
import java.util.Objects;

public class Test {

    public boolean compareFruit(Fruit apple){
        Fruit pear=new Fruit();
        pear.setName("pear");
        pear.setPrice(111);
        pear.setBranch("big pear");
        pear.setCount(21);

        Class appleClss=apple.getClass();
        Field[] appleFields=appleClss.getDeclaredFields();


        for (Field f:appleFields) {
            try{
                f.setAccessible(true);
//                System.out.println("field:"+f.getName()+";apple value:"+f.get(apple)+";pear value:"+f.get(pear));
                if(!Objects.equals(f.get(apple),f.get(pear))){
                    return false;
                }

            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }

        return true;
    }

    public Fruit factory(){
        Fruit apple=new Fruit();
        apple.setName("apple");
        apple.setPrice(10);
        apple.setBranch("big apple");
        apple.setCount(20);
        return apple;
    }

    public static void main(String[] args) {
        Test test=new Test();
        Fruit apple=test.factory();
        System.out.println(test.compareFruit(apple));
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/318544.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号