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