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