2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.gardena.internal.util;
15 import java.lang.reflect.Field;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.gardena.internal.exception.GardenaException;
22 * Utility class to read nested properties.
24 * @author Gerhard Riegler - Initial contribution
27 public class PropertyUtils {
30 * Returns true if the property is null.
32 public static boolean isNull(@Nullable Object instance, String propertyPath) throws GardenaException {
33 return getPropertyValue(instance, propertyPath, Object.class) == null;
37 * Returns the property value from the object instance, nested properties are possible.
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);
46 * Iterates through the nested properties and returns the field value.
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) {
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);
62 } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
63 throw new GardenaException(ex.getMessage(), ex);