BeanUtils_BeanUtils

BeanUtils_BeanUtilsBeanUtils类依赖的jar包注意:其中第二个包一定是commons-collections-xxx.jar,之前使用了commons-collectionsx-xxx.jar在web上显示未找到类BeanUtils类当中的主要方法populate(Objectbean,Map<String,?extendsObject>properties):可以将pr…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

BeanUtils类依赖的jar包

在这里插入图片描述

  • 注意:其中第二个包一定是commons-collections-xxx.jar,之前使用了commons-collectionsx-xxx.jar在web上显示未找到类

BeanUtils类当中的主要方法

  • populate(Object bean, Map<String, ? extends Object> properties):可以将properties当中的内容通过key-value的性质赋值给bean对象
  • setProperty(Object bean, String name, Object value):将bean对象当中属性名为name的属性值修改为value
  • getProperty(Object bean, String name):获取bean对象当中的名为name的属性的值

BeanUtils的使用方法

使用BeanUtils时变量和属性的区别

首先我们来看一下一个Student类的定义:

public class Student { 
   
    private String name;
    private int age;
    private String localAddress;

    public Student() { 
   
        name = "cjd";
        age = 20;
        localAddress = "china";
    }

    public void setName(String name) { 
   
        this.name = name;
    }
    public String getName() { 
   
        return name;
    }

    public void setAge(int age) { 
   
        this.age = age;
    }
    public int getAge() { 
   
        return age;
    }

    public void setHost(String localAddress) { 
   
        this.localAddress = localAddress;
    }
    public String getHost() { 
   
        return localAddress;
    }

    public String toString() { 
   
        return name + " " + age + " " + localAddress;
    }
}

很简单我们为Student对象设置了三个变量,分别是name,age,address,但是属性就没有那么简单了。
在BeanUtils当中其实属性名字与变量名字并没有太大的关系,属性是这么定义的举个例子我们看到了方法getHost(),我们去掉get之后获得Host,将H变成小写,就得到了属性host,因此属性是直接跟一个变量的getter和setter有关系的。
由此我们知道如果我们想要获得localAddress的值,应该是使用如下的代码:

public class Main { 
   
    public static void main(String[] args) { 
   
        Student student = new Student();
        System.out.println(student);
        try { 
   
            System.out.println(BeanUtils.getProperty(student, "host"));
        } catch (IllegalAccessException e) { 
   
            e.printStackTrace();
        } catch (InvocationTargetException e) { 
   
            e.printStackTrace();
        } catch (NoSuchMethodException e) { 
   
            e.printStackTrace();
        }
    }
}

BeanUtils当中的方法使用注意事项

  • 传入BeanUtils方法当中的bean类一定是public修饰的
  • 其中的属性值一定是private修饰的
  • 其中的getter和setter方法一定是public修饰的
  • getter和setter方法的命名一定是符合命名规范的(满足java命名规范就可以了)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/194979.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号