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