Bump odlparent to 5.0.0
[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         return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
86     }
87
88     /**
89      * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
90      * {@link ChildOf} interface.
91      *
92      * @param childClass
93      *            child class for which we want to find the parent class.
94      * @return Parent class, e.g. class of which the childClass is ChildOf.
95      */
96     public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
97         return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class);
98     }
99
100     /**
101      * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
102      * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
103      *
104      * @param child
105      *            Child object for which the parent needs to be located.
106      * @return Parent class, or null if a parent is not found.
107      */
108     public static Class<?> findHierarchicalParent(final DataObject child) {
109         if (child instanceof ChildOf) {
110             return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class);
111         }
112         return null;
113     }
114
115     /**
116      * Returns a QName associated to supplied type.
117      *
118      * @param dataType Data type class
119      * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
120      *         QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
121      *         have name. May return null if QName is not present.
122      */
123     public static QName findQName(final Class<?> dataType) {
124         return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
125     }
126
127     /**
128      * Checks if method is RPC invocation.
129      *
130      * @param possibleMethod
131      *            Method to check
132      * @return true if method is RPC invocation, false otherwise.
133      */
134     public static boolean isRpcMethod(final Method possibleMethod) {
135         return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
136                 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
137                 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
138                 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
139                 // non input type and two arguments for input type, resolveRpcInputClass() counting
140                 // with zero for non input and one for input type
141                 && possibleMethod.getParameterCount() <= 2;
142     }
143
144     /**
145      * Extracts Output class for RPC method.
146      *
147      * @param targetMethod
148      *            method to scan
149      * @return Optional.empty() if result type could not be get, or return type is Void.
150      */
151     @SuppressWarnings("rawtypes")
152     public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
153         checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
154         Type futureType = targetMethod.getGenericReturnType();
155         Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
156         Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
157         if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
158             return Optional.of((Class) rpcResultArgument);
159         }
160         return Optional.empty();
161     }
162
163     /**
164      * Extracts input class for RPC method.
165      *
166      * @param targetMethod
167      *            method to scan
168      * @return Optional.empty() if RPC has no input, RPC input type otherwise.
169      */
170     @SuppressWarnings("rawtypes")
171     public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
172         for (Class clazz : targetMethod.getParameterTypes()) {
173             if (DataContainer.class.isAssignableFrom(clazz)) {
174                 return Optional.of(clazz);
175             }
176         }
177         return Optional.empty();
178     }
179
180     public static QName getQName(final Class<? extends BaseIdentity> context) {
181         return findQName(context);
182     }
183
184     /**
185      * Checks if class is child of augmentation.
186      */
187     public static boolean isAugmentationChild(final Class<?> clazz) {
188         // FIXME: Current resolver could be still confused when child node was added by grouping
189         checkArgument(clazz != null);
190
191         @SuppressWarnings({ "rawtypes", "unchecked" })
192         Class<?> parent = findHierarchicalParent((Class) clazz);
193         if (parent == null) {
194             LOG.debug("Did not find a parent for class {}", clazz);
195             return false;
196         }
197
198         String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
199         String parentModelPackage = getModelRootPackageName(parent.getPackage());
200
201         return !clazzModelPackage.equals(parentModelPackage);
202     }
203
204     /**
205      * Returns root package name for supplied package.
206      *
207      * @param pkg
208      *            Package for which find model root package.
209      * @return Package of model root.
210      */
211     public static String getModelRootPackageName(final Package pkg) {
212         return getModelRootPackageName(pkg.getName());
213     }
214
215     /**
216      * Returns root package name for supplied package name.
217      *
218      * @param name
219      *            Package for which find model root package.
220      * @return Package of model root.
221      */
222     public static String getModelRootPackageName(final String name) {
223         checkArgument(name != null, "Package name should not be null.");
224         checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
225                 BindingMapping.PACKAGE_PREFIX, name);
226         Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
227         checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
228                 ROOT_PACKAGE_PATTERN_STRING);
229         return match.group(0);
230     }
231
232     @SuppressWarnings("checkstyle:illegalCatch")
233     public static QNameModule getQNameModule(final Class<?> clz) {
234         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
235                 || Action.class.isAssignableFrom(clz)) {
236             return findQName(clz).getModule();
237         }
238         try {
239             return BindingReflections.getModuleInfo(clz).getName().getModule();
240         } catch (Exception e) {
241             throw new IllegalStateException("Unable to get QName of defining model.", e);
242         }
243     }
244
245     /**
246      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
247      *
248      * @param cls data object class
249      * @return Instance of {@link YangModuleInfo} associated with model, from
250      *         which this class was derived.
251      */
252     public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
253         checkArgument(cls != null);
254         String packageName = getModelRootPackageName(cls.getPackage());
255         final String potentialClassName = getModuleInfoClassName(packageName);
256         return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
257             Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
258             return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
259         });
260     }
261
262     public static String getModuleInfoClassName(final String packageName) {
263         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
264     }
265
266     /**
267      * Check if supplied class is derived from YANG model.
268      *
269      * @param cls
270      *            Class to check
271      * @return true if class is derived from YANG model.
272      */
273     public static boolean isBindingClass(final Class<?> cls) {
274         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
275             return true;
276         }
277         return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
278     }
279
280     /**
281      * Checks if supplied method is callback for notifications.
282      *
283      * @param method method to check
284      * @return true if method is notification callback.
285      */
286     public static boolean isNotificationCallback(final Method method) {
287         checkArgument(method != null);
288         if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
289             Class<?> potentialNotification = method.getParameterTypes()[0];
290             if (isNotification(potentialNotification)
291                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
292                 return true;
293             }
294         }
295         return false;
296     }
297
298     /**
299      * Checks is supplied class is a {@link Notification}.
300      *
301      * @param potentialNotification class to examine
302      * @return True if the class represents a Notification.
303      */
304     public static boolean isNotification(final Class<?> potentialNotification) {
305         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
306         return Notification.class.isAssignableFrom(potentialNotification);
307     }
308
309     /**
310      * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
311      * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
312      *
313      * @return Set of {@link YangModuleInfo} available for current classloader.
314      */
315     public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
316         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
317     }
318
319     /**
320      * Loads {@link YangModuleInfo} infos available on supplied classloader.
321      *
322      * <p>
323      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
324      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
325      * {@link YangModuleInfo}.
326      *
327      * <p>
328      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
329      * collecting results of {@link YangModuleInfo#getImportedModules()}.
330      *
331      * @param loader
332      *            Classloader for which {@link YangModuleInfo} should be
333      *            retrieved.
334      * @return Set of {@link YangModuleInfo} available for supplied classloader.
335      */
336     public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
337         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
338         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
339                 loader);
340         for (YangModelBindingProvider bindingProvider : serviceLoader) {
341             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
342             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
343             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
344         }
345         return moduleInfoSet.build();
346     }
347
348     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
349             final Builder<YangModuleInfo> moduleInfoSet) {
350         moduleInfoSet.add(moduleInfo);
351         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
352             collectYangModuleInfo(dependency, moduleInfoSet);
353         }
354     }
355
356     /**
357      * Checks if supplied class represents RPC Input / RPC Output.
358      *
359      * @param targetType
360      *            Class to be checked
361      * @return true if class represents RPC Input or RPC Output class.
362      */
363     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
364         return DataContainer.class.isAssignableFrom(targetType)
365                 && !ChildOf.class.isAssignableFrom(targetType)
366                 && !Notification.class.isAssignableFrom(targetType)
367                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
368     }
369
370     /**
371      * Scans supplied class and returns an iterable of all data children classes.
372      *
373      * @param type
374      *            YANG Modeled Entity derived from DataContainer
375      * @return Iterable of all data children, which have YANG modeled entity
376      */
377     @SuppressWarnings("unchecked")
378     public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
379         checkArgument(type != null, "Target type must not be null");
380         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
381         List<Class<? extends DataObject>> ret = new LinkedList<>();
382         for (Method method : type.getMethods()) {
383             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
384                 BindingMapping.GETTER_PREFIX);
385             if (entity.isPresent()) {
386                 ret.add((Class<? extends DataObject>) entity.get());
387             }
388         }
389         return ret;
390     }
391
392     /**
393      * Scans supplied class and returns an iterable of all data children classes.
394      *
395      * @param type
396      *            YANG Modeled Entity derived from DataContainer
397      * @return Iterable of all data children, which have YANG modeled entity
398      */
399     public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
400         return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
401     }
402
403     private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
404         checkArgument(type != null, "Target type must not be null");
405         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
406             type);
407         Map<Class<?>, Method> ret = new HashMap<>();
408         for (Method method : type.getMethods()) {
409             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
410             if (entity.isPresent()) {
411                 ret.put(entity.get(), method);
412             }
413         }
414         return ret;
415     }
416
417     @Beta
418     public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
419         return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
420     }
421
422     @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
423     private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
424             final String prefix) {
425         final String methodName = method.getName();
426         if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
427             return Optional.empty();
428         }
429
430         Class returnType = method.getReturnType();
431         if (DataContainer.class.isAssignableFrom(returnType)) {
432             return Optional.of(returnType);
433         }
434         if (List.class.isAssignableFrom(returnType)) {
435             try {
436                 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
437                     Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
438                     if (listResult instanceof Class && DataContainer.class.isAssignableFrom((Class) listResult)) {
439                         return Optional.of((Class) listResult);
440                     }
441                     return 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 }