Add InstanceIdentifier.verifyTarget() 73/89573/3
authorRobert Varga <robert.varga@pantheon.tech>
Sun, 3 May 2020 08:04:18 +0000 (10:04 +0200)
committerRobert Varga <robert.varga@pantheon.tech>
Sun, 3 May 2020 09:46:07 +0000 (11:46 +0200)
There are a number of places where users are casting InstanceIdentifiers,
just to restore type-safety after a type-unsafe operation, such as
going through serialization. Add InstanceIdentifier.verifyTarget(),
which restores type safety.

Change-Id: I2bfa69eb938b4a6b86b88e4054369b3abadf7c7d
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
binding/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/InstanceIdentifier.java

index 8627422ee753f926f43654ea83c90b81e7d5cdf0..626aaf043ae23a92d3851a5df51fc06e34a41db7 100644 (file)
@@ -8,10 +8,12 @@
 package org.opendaylight.yangtools.yang.binding;
 
 import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Verify.verify;
 import static java.util.Objects.requireNonNull;
 
 import com.google.common.base.MoreObjects;
 import com.google.common.base.MoreObjects.ToStringHelper;
+import com.google.common.base.VerifyException;
 import com.google.common.collect.ImmutableCollection;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
@@ -90,6 +92,20 @@ public class InstanceIdentifier<T extends DataObject> implements Path<InstanceId
         return targetType;
     }
 
+    /**
+     * Perform a safe target type adaptation of this instance identifier to target type. This method is useful when
+     * dealing with type-squashed instances.
+     *
+     * @return Path argument with target type
+     * @throws VerifyException if this instance identifier cannot be adapted to target type
+     * @throws NullPointerException if {@code target} is null
+     */
+    @SuppressWarnings("unchecked")
+    public final <N extends DataObject> @NonNull InstanceIdentifier<N> verifyTarget(final Class<N> target) {
+        verify(target.equals(targetType), "Cannot adapt %s to %s", this, target);
+        return (InstanceIdentifier<N>) this;
+    }
+
     /**
      * Return the path argument chain which makes up this instance identifier.
      *