]> git.basschouten.com Git - openhab-addons.git/blob
59b153f11ba4c2581eee25c40ac35711c10d8c1b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.gardena.internal.util;
14
15 import java.lang.reflect.Field;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.gardena.internal.exception.GardenaException;
20
21 /**
22  * Utility class to read nested properties.
23  *
24  * @author Gerhard Riegler - Initial contribution
25  */
26 @NonNullByDefault
27 public class PropertyUtils {
28
29     /**
30      * Returns true if the property is null.
31      */
32     public static boolean isNull(@Nullable Object instance, String propertyPath) throws GardenaException {
33         return getPropertyValue(instance, propertyPath, Object.class) == null;
34     }
35
36     /**
37      * Returns the property value from the object instance, nested properties are possible.
38      */
39     public static <T> @Nullable T getPropertyValue(@Nullable Object instance, String propertyPath, Class<T> resultClass)
40             throws GardenaException {
41         String[] properties = propertyPath.split("\\.");
42         return getPropertyValue(instance, properties, resultClass, 0);
43     }
44
45     /**
46      * Iterates through the nested properties and returns the field value.
47      */
48     @SuppressWarnings("unchecked")
49     private static <T> @Nullable T getPropertyValue(@Nullable Object instance, String[] properties,
50             Class<T> resultClass, int nestedIndex) throws GardenaException {
51         if (instance == null) {
52             return null;
53         }
54         try {
55             String propertyName = properties[nestedIndex];
56             Field field = instance.getClass().getField(propertyName);
57             Object result = field.get(instance);
58             if (nestedIndex + 1 < properties.length) {
59                 return getPropertyValue(result, properties, resultClass, nestedIndex + 1);
60             }
61             return (T) result;
62         } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
63             throw new GardenaException(ex.getMessage(), ex);
64         }
65     }
66 }