af800bee26fbd08ac879ff93a7cd8ded32e791a2
[mdsal.git] / binding / mdsal-binding-spec-util / src / main / java / org / opendaylight / mdsal / binding / spec / reflect / BindingReflections.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.spec.reflect;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Type;
23 import java.util.Arrays;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Optional;
30 import java.util.ServiceLoader;
31 import java.util.Set;
32 import java.util.concurrent.TimeUnit;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import org.checkerframework.checker.regex.qual.Regex;
36 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
37 import org.opendaylight.yangtools.util.ClassLoaderUtils;
38 import org.opendaylight.yangtools.yang.binding.Action;
39 import org.opendaylight.yangtools.yang.binding.Augmentable;
40 import org.opendaylight.yangtools.yang.binding.Augmentation;
41 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
42 import org.opendaylight.yangtools.yang.binding.ChildOf;
43 import org.opendaylight.yangtools.yang.binding.DataContainer;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.binding.Notification;
46 import org.opendaylight.yangtools.yang.binding.RpcService;
47 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
48 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.common.YangConstants;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 public final class BindingReflections {
56
57     private static final long EXPIRATION_TIME = 60;
58
59     @Regex
60     private static final String ROOT_PACKAGE_PATTERN_STRING =
61             "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
62     private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
63     private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
64
65     private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
66             .weakKeys()
67             .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
68             .build(new ClassToQNameLoader());
69
70     private BindingReflections() {
71         throw new UnsupportedOperationException("Utility class.");
72     }
73
74     /**
75      * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
76      * implemented {@link Augmentation} interface.
77      *
78      * @param augmentation
79      *            {@link Augmentation} subclass for which we want to determine
80      *            augmentation target.
81      * @return Augmentation target - class which augmentation provides additional extensions.
82      */
83     public static Class<? extends Augmentable<?>> findAugmentationTarget(
84             final Class<? extends Augmentation<?>> augmentation) {
85         final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
86             Augmentation.class);
87         return opt.orElse(null);
88     }
89
90     /**
91      * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
92      * {@link ChildOf} interface.
93      *
94      * @param childClass
95      *            child class for which we want to find the parent class.
96      * @return Parent class, e.g. class of which the childClass is ChildOf.
97      */
98     public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
99         return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class).orElse(null);
100     }
101
102     /**
103      * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
104      * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
105      *
106      * @param child
107      *            Child object for which the parent needs to be located.
108      * @return Parent class, or null if a parent is not found.
109      */
110     public static Class<?> findHierarchicalParent(final DataObject child) {
111         if (child instanceof ChildOf) {
112             return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class).orElse(null);
113         }
114         return null;
115     }
116
117     /**
118      * Returns a QName associated to supplied type.
119      *
120      * @param dataType Data type class
121      * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
122      *         QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
123      *         have name. May return null if QName is not present.
124      */
125     public static QName findQName(final Class<?> dataType) {
126         return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
127     }
128
129     /**
130      * Checks if method is RPC invocation.
131      *
132      * @param possibleMethod
133      *            Method to check
134      * @return true if method is RPC invocation, false otherwise.
135      */
136     public static boolean isRpcMethod(final Method possibleMethod) {
137         return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
138                 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
139                 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
140                 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
141                 // non input type and two arguments for input type, resolveRpcInputClass() counting
142                 // with zero for non input and one for input type
143                 && possibleMethod.getParameterCount() <= 2;
144     }
145
146     /**
147      * Extracts Output class for RPC method.
148      *
149      * @param targetMethod
150      *            method to scan
151      * @return Optional.empty() if result type could not be get, or return type is Void.
152      */
153     @SuppressWarnings("rawtypes")
154     public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
155         checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
156         Type futureType = targetMethod.getGenericReturnType();
157         Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
158         Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
159         if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
160             return Optional.of((Class) rpcResultArgument);
161         }
162         return Optional.empty();
163     }
164
165     /**
166      * Extracts input class for RPC method.
167      *
168      * @param targetMethod
169      *            method to scan
170      * @return Optional.empty() if RPC has no input, RPC input type otherwise.
171      */
172     @SuppressWarnings("rawtypes")
173     public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
174         for (Class clazz : targetMethod.getParameterTypes()) {
175             if (DataContainer.class.isAssignableFrom(clazz)) {
176                 return Optional.of(clazz);
177             }
178         }
179         return Optional.empty();
180     }
181
182     public static QName getQName(final Class<? extends BaseIdentity> context) {
183         return findQName(context);
184     }
185
186     /**
187      * Checks if class is child of augmentation.
188      */
189     public static boolean isAugmentationChild(final Class<?> clazz) {
190         // FIXME: Current resolver could be still confused when child node was added by grouping
191         checkArgument(clazz != null);
192
193         @SuppressWarnings({ "rawtypes", "unchecked" })
194         Class<?> parent = findHierarchicalParent((Class) clazz);
195         if (parent == null) {
196             LOG.debug("Did not find a parent for class {}", clazz);
197             return false;
198         }
199
200         String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
201         String parentModelPackage = getModelRootPackageName(parent.getPackage());
202
203         return !clazzModelPackage.equals(parentModelPackage);
204     }
205
206     /**
207      * Returns root package name for supplied package.
208      *
209      * @param pkg
210      *            Package for which find model root package.
211      * @return Package of model root.
212      */
213     public static String getModelRootPackageName(final Package pkg) {
214         return getModelRootPackageName(pkg.getName());
215     }
216
217     /**
218      * Returns root package name for supplied package name.
219      *
220      * @param name
221      *            Package for which find model root package.
222      * @return Package of model root.
223      */
224     public static String getModelRootPackageName(final String name) {
225         checkArgument(name != null, "Package name should not be null.");
226         checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
227                 BindingMapping.PACKAGE_PREFIX, name);
228         Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
229         checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
230                 ROOT_PACKAGE_PATTERN_STRING);
231         return match.group(0);
232     }
233
234     @SuppressWarnings("checkstyle:illegalCatch")
235     public static QNameModule getQNameModule(final Class<?> clz) {
236         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
237                 || Action.class.isAssignableFrom(clz)) {
238             return findQName(clz).getModule();
239         }
240         try {
241             return BindingReflections.getModuleInfo(clz).getName().getModule();
242         } catch (Exception e) {
243             throw new IllegalStateException("Unable to get QName of defining model.", e);
244         }
245     }
246
247     /**
248      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
249      *
250      * @param cls data object class
251      * @return Instance of {@link YangModuleInfo} associated with model, from
252      *         which this class was derived.
253      */
254     public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
255         checkArgument(cls != null);
256         String packageName = getModelRootPackageName(cls.getPackage());
257         final String potentialClassName = getModuleInfoClassName(packageName);
258         return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
259             Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
260             return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
261         });
262     }
263
264     public static String getModuleInfoClassName(final String packageName) {
265         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
266     }
267
268     /**
269      * Check if supplied class is derived from YANG model.
270      *
271      * @param cls
272      *            Class to check
273      * @return true if class is derived from YANG model.
274      */
275     public static boolean isBindingClass(final Class<?> cls) {
276         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
277             return true;
278         }
279         return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
280     }
281
282     /**
283      * Checks if supplied method is callback for notifications.
284      *
285      * @param method method to check
286      * @return true if method is notification callback.
287      */
288     public static boolean isNotificationCallback(final Method method) {
289         checkArgument(method != null);
290         if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
291             Class<?> potentialNotification = method.getParameterTypes()[0];
292             if (isNotification(potentialNotification)
293                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
294                 return true;
295             }
296         }
297         return false;
298     }
299
300     /**
301      * Checks is supplied class is a {@link Notification}.
302      *
303      * @param potentialNotification class to examine
304      * @return True if the class represents a Notification.
305      */
306     public static boolean isNotification(final Class<?> potentialNotification) {
307         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
308         return Notification.class.isAssignableFrom(potentialNotification);
309     }
310
311     /**
312      * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
313      * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
314      *
315      * @return Set of {@link YangModuleInfo} available for current classloader.
316      */
317     public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
318         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
319     }
320
321     /**
322      * Loads {@link YangModuleInfo} infos available on supplied classloader.
323      *
324      * <p>
325      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
326      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
327      * {@link YangModuleInfo}.
328      *
329      * <p>
330      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
331      * collecting results of {@link YangModuleInfo#getImportedModules()}.
332      *
333      * @param loader
334      *            Classloader for which {@link YangModuleInfo} should be
335      *            retrieved.
336      * @return Set of {@link YangModuleInfo} available for supplied classloader.
337      */
338     public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
339         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
340         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
341                 loader);
342         for (YangModelBindingProvider bindingProvider : serviceLoader) {
343             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
344             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
345             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
346         }
347         return moduleInfoSet.build();
348     }
349
350     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
351             final Builder<YangModuleInfo> moduleInfoSet) {
352         moduleInfoSet.add(moduleInfo);
353         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
354             collectYangModuleInfo(dependency, moduleInfoSet);
355         }
356     }
357
358     /**
359      * Checks if supplied class represents RPC Input / RPC Output.
360      *
361      * @param targetType
362      *            Class to be checked
363      * @return true if class represents RPC Input or RPC Output class.
364      */
365     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
366         return DataContainer.class.isAssignableFrom(targetType)
367                 && !ChildOf.class.isAssignableFrom(targetType)
368                 && !Notification.class.isAssignableFrom(targetType)
369                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
370     }
371
372     /**
373      * Scans supplied class and returns an iterable of all data children classes.
374      *
375      * @param type
376      *            YANG Modeled Entity derived from DataContainer
377      * @return Iterable of all data children, which have YANG modeled entity
378      */
379     @SuppressWarnings("unchecked")
380     public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
381         checkArgument(type != null, "Target type must not be null");
382         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
383         List<Class<? extends DataObject>> ret = new LinkedList<>();
384         for (Method method : type.getMethods()) {
385             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
386                 BindingMapping.GETTER_PREFIX);
387             if (entity.isPresent()) {
388                 ret.add((Class<? extends DataObject>) entity.get());
389             }
390         }
391         return ret;
392     }
393
394     /**
395      * Scans supplied class and returns an iterable of all data children classes.
396      *
397      * @param type
398      *            YANG Modeled Entity derived from DataContainer
399      * @return Iterable of all data children, which have YANG modeled entity
400      */
401     public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
402         return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
403     }
404
405     private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
406         checkArgument(type != null, "Target type must not be null");
407         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
408             type);
409         Map<Class<?>, Method> ret = new HashMap<>();
410         for (Method method : type.getMethods()) {
411             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
412             if (entity.isPresent()) {
413                 ret.put(entity.get(), method);
414             }
415         }
416         return ret;
417     }
418
419     @Beta
420     public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
421         return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
422     }
423
424     @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
425     private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
426             final String prefix) {
427         final String methodName = method.getName();
428         if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
429             return Optional.empty();
430         }
431
432         Class returnType = method.getReturnType();
433         if (DataContainer.class.isAssignableFrom(returnType)) {
434             return Optional.of(returnType);
435         }
436         if (List.class.isAssignableFrom(returnType)) {
437             try {
438                 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
439                     return ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()).flatMap(
440                         result -> result instanceof Class && DataContainer.class.isAssignableFrom((Class) result)
441                             ? Optional.of((Class) result) : Optional.empty());
442                 });
443             } catch (Exception e) {
444                 /*
445                  * It is safe to log this this exception on debug, since this
446                  * method should not fail. Only failures are possible if the
447                  * runtime / backing.
448                  */
449                 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
450             }
451         }
452         return Optional.empty();
453     }
454
455     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
456
457         @Override
458         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
459             return resolveQNameNoCache(key);
460         }
461
462         /**
463          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
464          * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
465          * {@link #computeQName(Class)} to compute QName for missing types.
466          */
467         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
468             try {
469                 final Field field;
470                 try {
471                     field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
472                 } catch (NoSuchFieldException e) {
473                     LOG.debug("{} does not have a {} field, falling back to computation", key,
474                         BindingMapping.QNAME_STATIC_FIELD_NAME, e);
475                     return Optional.of(computeQName(key));
476                 }
477
478                 final Object obj = field.get(null);
479                 if (obj instanceof QName) {
480                     return Optional.of((QName) obj);
481                 }
482             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
483                 /*
484                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
485                  * possible if the runtime / backing is inconsistent.
486                  */
487                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
488             }
489             return Optional.empty();
490         }
491
492         /**
493          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
494          * supplied class.
495          *
496          * <p>
497          * If class is
498          * <ul>
499          * <li>rpc input: local name is "input".
500          * <li>rpc output: local name is "output".
501          * <li>augmentation: local name is "module name".
502          * </ul>
503          *
504          * <p>
505          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
506          * QName.
507          *
508          * @throws IllegalStateException If YangModuleInfo could not be resolved
509          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
510          */
511         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
512         @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
513         private static QName computeQName(final Class key) {
514             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
515
516             YangModuleInfo moduleInfo;
517             try {
518                 moduleInfo = getModuleInfo(key);
519             } catch (Exception e) {
520                 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
521                     e);
522             }
523             final QName module = moduleInfo.getName();
524             if (Augmentation.class.isAssignableFrom(key)) {
525                 return module;
526             } else if (isRpcType(key)) {
527                 final String className = key.getSimpleName();
528                 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
529                     return YangConstants.operationOutputQName(module.getModule()).intern();
530                 }
531
532                 return YangConstants.operationInputQName(module.getModule()).intern();
533             }
534
535             /*
536              * Fallback for Binding types which do not have QNAME field
537              */
538             return module;
539         }
540     }
541
542     /**
543      * Extracts augmentation from Binding DTO field using reflection.
544      *
545      * @param input
546      *            Instance of DataObject which is augmentable and may contain
547      *            augmentation
548      * @return Map of augmentations if read was successful, otherwise empty map.
549      */
550     public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
551         return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
552     }
553
554     /**
555      * Determines if two augmentation classes or case classes represents same
556      * data.
557      *
558      * <p>
559      * Two augmentations or cases could be substituted only if and if:
560      * <ul>
561      * <li>Both implements same interfaces</li>
562      * <li>Both have same children</li>
563      * <li>If augmentations: Both have same augmentation target class. Target
564      * class was generated for data node in grouping.</li>
565      * <li>If cases: Both are from same choice. Choice class was generated for
566      * data node in grouping.</li>
567      * </ul>
568      *
569      * <p>
570      * <b>Explanation:</b> Binding Specification reuses classes generated for
571      * groupings as part of normal data tree, this classes from grouping could
572      * be used at various locations and user may not be aware of it and may use
573      * incorrect case or augmentation in particular subtree (via copy
574      * constructors, etc).
575      *
576      * @param potential
577      *            Class which is potential substitution
578      * @param target
579      *            Class which should be used at particular subtree
580      * @return true if and only if classes represents same data.
581      */
582     @SuppressWarnings({ "rawtypes", "unchecked" })
583     public static boolean isSubstitutionFor(final Class potential, final Class target) {
584         Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
585         Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
586         if (!subImplemented.equals(targetImplemented)) {
587             return false;
588         }
589         if (Augmentation.class.isAssignableFrom(potential)
590                 && !BindingReflections.findAugmentationTarget(potential).equals(
591                         BindingReflections.findAugmentationTarget(target))) {
592             return false;
593         }
594         for (Method potentialMethod : potential.getMethods()) {
595             try {
596                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
597                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
598                     return false;
599                 }
600             } catch (NoSuchMethodException e) {
601                 // Counterpart method is missing, so classes could not be substituted.
602                 return false;
603             } catch (SecurityException e) {
604                 throw new IllegalStateException("Could not compare methods", e);
605             }
606         }
607         return true;
608     }
609 }