Which Java library allows me to initialize the properties of an object from a properties file?

Is there a Java library that allows you to “deserialize” a properties file directly into an instance of an object?

Example: they say that you have an init.properties file:

username=fisk
password=frosk

and a Java class with some properties:

class Connection {

    private String username;
    private String password;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

I want to do this:

Connection c = MagicConfigurator.configure("init.properties", new Connection())

and MagicConfigurator will apply all values ​​from the properties file to the Connection instance.

Is there a library with such a class?

+3
source share
8 answers

This is pretty simple using commons-beanutils . The library even takes care of type conversions. In addition, you can even set the properties of nested objects and arrays.

public static void setProperties(Object bean, Properties properties) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
  for (Map.Entry<Object, Object> e : properties.entrySet()) {
    if (e.getKey() instanceof String) {
      BeanUtils.setProperty(bean, (String) e.getKey(), e.getValue());
    }
  }
}

, :

username=john
keys[0]=47
keys[1]=11
person.name=John
person.age=42

" ". , Person.

+8

? :

:

  • setter ( )
  • Method (API )
  • (API- )

, Properties.

+1

BeanInfo.

. - .

public void readProperties(Object o, Properties p) throws IntrospectionException, InvocationTargetException, IllegalAccessException
{
    BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass());
    for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors())
    {
        String value = p.getProperty(propertyDescriptor.getName());
        if ( value != null && propertyDescriptor.getWriteMethod() != null )
        {
            propertyDescriptor.getWriteMethod().invoke(o, value);
        }
    }
}
+1
0

: Properties . /.

, - , , . Hashtable, a Hashtable. , , , "is-a" .

0

, ( Andreas_D), , "" .

, OGNL.

http://www.opensymphony.com/ognl/

  • .
  • OGNL.
  • OGNL . (- stack.setValue( "property", value );)

, , OGNL. - stack.setValue( "property.name", value );, getProperty(), get/setName().

0
source

If you use xml instead of properties, you can use JaxB.

0
source

Source: https://habr.com/ru/post/1746524/


All Articles