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

  • Post author:
  • Post category:java




介绍

官网: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));
    }
}



运行

可以看见两种方式赋值均成功了

在这里插入图片描述



版权声明:本文为sndayYU原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。