commons-beanutils.jarを利用してjava beanを操作する方法

3104 ワード

commons-beanutils.jarを利用してjava beanを操作する方法
  • 紹介します.
  • コード
  • pom.xml
  • Student.java
  • Commons Beanutils Test.java
  • 運転
  • 紹介する
    公式サイト:http://commons.apache.org/proper/commons-beanutils/The Java landage provides Reflection and Intropspection API.However,the API can.land.reflect and java.beans packages in the JDK Javadocs).However,these API can be quite complext unders and and and and and providers
    コード
    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;
    }
    
    
    Commons Beanutils Test.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张图片.