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

本文介绍了如何利用Java反射机制来比较两个对象的属性值是否相同。通过创建实体类Fruit作为示例,展示了反射在对象属性比较中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先定义一个实体类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));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值