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

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

  • 介绍
  • 代码
      • pom.xml
      • Student.java
      • CommonsBeanutilsTest.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


        
        
            junit
            junit
            4.12
            test
        
        
        
            org.projectlombok
            lombok
            1.16.20
        
        
            org.slf4j
            slf4j-simple
            1.7.25
        
        
            com.alibaba
            fastjson
            1.2.35
        

        
        
            commons-beanutils
            commons-beanutils
            1.9.3
        

    

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));
    }
}

运行

可以看见两种方式赋值均成功了
利用commons-beanutils.jar操作java bean方法_第1张图片

你可能感兴趣的:(java,Java)