Class PropertyUtil


  • public final class PropertyUtil
    extends Object
    Helper class providing convenient methods for reading from / writing to java beans.

    Caution:

    Use reflection only if there is no other way. Even if some of the problems are minimized by using this type. It should be used either in test-code, what is we actually do, and not production code. An other reason could be framework code. as for that you should exactly know what you do.

    Author:
    Oliver Wolff
    • Method Detail

      • readProperty

        public static Object readProperty​(Object bean,
                                          String propertyName)
        Parameters:
        bean - instance to be read from, must not be null
        propertyName - to be read, must not be null nor empty nor blank
        Returns:
        the object read from the property
        Throws:
        IllegalArgumentException - in case the property does not exist (determined by a read method)
        IllegalStateException - in case some Exception occurred while reading
      • writeProperty

        public static Object writeProperty​(Object bean,
                                           String propertyName,
                                           Object propertyValue)
        Parameters:
        bean - instance to be read from, must not be null
        propertyName - to be read, must not be null nor empty nor blank
        propertyValue - to be set
        Returns:
        In case the property set method is void the given bean will be returned. Otherwise, the return value of the method invocation, assuming the setMethods is a builder type.
        Throws:
        IllegalArgumentException - in case the property does not exist (determined by a write method)
        IllegalStateException - in case some Exception occurred while writing
      • resolvePropertyType

        public static Optional<Class<?>> resolvePropertyType​(Class<?> beanType,
                                                             String propertyName)
        Tries to determine the type of given property
        Parameters:
        beanType - to be checked, must not be null
        propertyName - to be checked, must not be null
        Returns:
        an Optional on the actual type of the property. First it checks an access-methods, then it tries to directly access the field, and if that fails it uses the first read method found, Optional.empty() otherwise.