利用commons-beanutils.jar操作java bean方法

利用commons-beanutils.jar操作java bean方法

介绍

官网:http://commons.apache.org/proper/commons-beanutils/
The Java language provides Reflection and Introspection APIs (see the java.lang.reflect and java.beans packages in the JDK Javadocs). However, these APIs can be quite complex to understand and utilize. The BeanUtils component provides easy-to-use wrappers around these capabilities.

代码

pom.xml

<dependencies>
        <!-- test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.35</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>

    </dependencies>

Student.java

package com.ydfind.object.model;

import lombok.Data;

@Data
public class Student {

    private String name;

    private Integer id;

    private String address;

    private String phone;

    private Integer age;
}

CommonsBeanutilsTest.java

package com.ydfind.object;

import com.alibaba.fastjson.JSON;
import com.ydfind.object.model.Student;
import org.apache.commons.beanutils.MethodUtils;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class CommonsBeanutilsTest {

    @Test
    public void testCommonsBeanutils() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Student student = new Student();
        System.out.println(JSON.toJSONString(student));
        // 通过方法名和参数类型获得可访问方法
        Method method = MethodUtils.getAccessibleMethod(Student.class,
                "setId", Integer.class);
        method.invoke(student, 18);
        // 可以直接通过invokeMethod执行方法
        MethodUtils.invokeMethod(student, "setName", "张三");
        System.out.println(JSON.toJSONString(student));
    }
}

运行

可以看见两种方式赋值均成功了
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值