BeanUtils的使用、Java中的路径问题

一、BeanUtils的使用

  BeanUtils主要解决的问题: 把对象的属性数据封装到对象中。

  BeanUtils的好处:

    1. BeanUtils设置属性值的时候,如果属性是基本数据 类型,BeanUtils会自动帮我转换数据类型。

    2. BeanUtils设置属性值的时候底层也是依赖于get或者Set方法设置以及获取属性值的。

    3. BeanUtils设置属性值,如果设置的属性是其他的引用 类型数据,那么这时候必须要注册一个类型转换器。

  BeanUtilss使用的步骤

    1. 导包commons-logging.jar 

    2. 导包commons-beanutils-1.9.2.jar

示例说明:

  @Test
    public void testBeanUtils() throws InvocationTargetException, IllegalAccessException {
        Person p = new Person();
        String id = "110";
        String name = "张三";
        String salary = "10000";
        String birthday = "2010-10-19";

        BeanUtils.setProperty(p, "id", id);
        BeanUtils.setProperty(p, "name", name);
        BeanUtils.setProperty(p, "salary", salary);

        ConvertUtils.register(new Converter() {
            @Override
            public <T> T convert(Class<T> type, Object value) {
                T t = null;
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    t = (T) format.parse((String) value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return t;
            }
        }

                , Date.class);
        BeanUtils.setProperty(p, "birthday", birthday);
        System.out.println(p);
    }

二、Java中的路径问题

在Java程序中,一般情况下使用绝对路径还是相对路径都不太合适,因为Java程序的jar包所放的位置不确定,执行java程序时当前的路径也不确定,所以不合适。一般在Java程序中我们会把资源放到classpath中,然后使用classpath路径查找资源。

Classpath路径:就是使用classpath目前的路径。

示例说明:

public class Demo {
public static void main(String[] args) throws IOException {
Class clazz = new Demo().getClass();
//prop.properties文件在src根目录下
InputStream is = clazz.getResourceAsStream("/prop.properties");
Properties properties = new Properties();
properties.load(is);
String name = properties.getProperty("username");
String pwd = properties.getProperty("password");
System.out.println("用户名:" + name + ",密码:" + pwd);
}
}
原文地址:https://www.cnblogs.com/FlySheep/p/4853505.html