2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.spec.reflect;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.annotations.Beta;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.CacheLoader;
18 import com.google.common.cache.LoadingCache;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.ImmutableSet.Builder;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import java.lang.reflect.Field;
23 import java.lang.reflect.Method;
24 import java.lang.reflect.ParameterizedType;
25 import java.lang.reflect.Type;
26 import java.util.Arrays;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.LinkedList;
30 import java.util.List;
32 import java.util.Optional;
33 import java.util.ServiceLoader;
35 import java.util.concurrent.TimeUnit;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import org.checkerframework.checker.regex.qual.Regex;
39 import org.eclipse.jdt.annotation.NonNull;
40 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
41 import org.opendaylight.yangtools.util.ClassLoaderUtils;
42 import org.opendaylight.yangtools.yang.binding.Action;
43 import org.opendaylight.yangtools.yang.binding.Augmentable;
44 import org.opendaylight.yangtools.yang.binding.Augmentation;
45 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
46 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
47 import org.opendaylight.yangtools.yang.binding.ChildOf;
48 import org.opendaylight.yangtools.yang.binding.DataContainer;
49 import org.opendaylight.yangtools.yang.binding.DataObject;
50 import org.opendaylight.yangtools.yang.binding.Notification;
51 import org.opendaylight.yangtools.yang.binding.RpcService;
52 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
53 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.QNameModule;
56 import org.opendaylight.yangtools.yang.common.YangConstants;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 public final class BindingReflections {
62 private static final long EXPIRATION_TIME = 60;
65 private static final String ROOT_PACKAGE_PATTERN_STRING =
66 "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
67 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
68 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
70 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
72 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
73 .build(new ClassToQNameLoader());
75 private static final LoadingCache<ClassLoader, ImmutableSet<YangModuleInfo>> MODULE_INFO_CACHE =
76 CacheBuilder.newBuilder().weakKeys().weakValues().build(
77 new CacheLoader<ClassLoader, ImmutableSet<YangModuleInfo>>() {
79 public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
80 return loadModuleInfos(key);
84 private BindingReflections() {
89 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
90 * implemented {@link Augmentation} interface.
93 * {@link Augmentation} subclass for which we want to determine
94 * augmentation target.
95 * @return Augmentation target - class which augmentation provides additional extensions.
97 public static Class<? extends Augmentable<?>> findAugmentationTarget(
98 final Class<? extends Augmentation<?>> augmentation) {
99 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
101 return opt.orElse(null);
105 * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
106 * {@link ChildOf} interface.
109 * child class for which we want to find the parent class.
110 * @return Parent class, e.g. class of which the childClass is ChildOf.
112 public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
113 return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class).orElse(null);
117 * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
118 * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
121 * Child object for which the parent needs to be located.
122 * @return Parent class, or null if a parent is not found.
124 public static Class<?> findHierarchicalParent(final DataObject child) {
125 if (child instanceof ChildOf) {
126 return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class).orElse(null);
132 * Returns a QName associated to supplied type.
134 * @param dataType Data type class
135 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
136 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
137 * have name. May return null if QName is not present.
139 public static QName findQName(final Class<?> dataType) {
140 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
144 * Checks if method is RPC invocation.
146 * @param possibleMethod
148 * @return true if method is RPC invocation, false otherwise.
150 public static boolean isRpcMethod(final Method possibleMethod) {
151 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
152 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
153 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
154 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
155 // non input type and two arguments for input type, resolveRpcInputClass() counting
156 // with zero for non input and one for input type
157 && possibleMethod.getParameterCount() <= 2;
161 * Extracts Output class for RPC method.
163 * @param targetMethod
165 * @return Optional.empty() if result type could not be get, or return type is Void.
167 @SuppressWarnings("rawtypes")
168 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
169 checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
170 Type futureType = targetMethod.getGenericReturnType();
171 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
172 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
173 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
174 return Optional.of((Class) rpcResultArgument);
176 return Optional.empty();
180 * Extracts input class for RPC method.
182 * @param targetMethod
184 * @return Optional.empty() if RPC has no input, RPC input type otherwise.
186 @SuppressWarnings("rawtypes")
187 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
188 for (Class clazz : targetMethod.getParameterTypes()) {
189 if (DataContainer.class.isAssignableFrom(clazz)) {
190 return Optional.of(clazz);
193 return Optional.empty();
196 public static @NonNull QName getQName(final Class<? extends BaseIdentity> bindingClass) {
197 final Optional<QName> qname = CLASS_TO_QNAME.getUnchecked(requireNonNull(bindingClass));
198 checkState(qname.isPresent(), "Failed to resolve QName of %s", bindingClass);
203 * Checks if class is child of augmentation.
205 public static boolean isAugmentationChild(final Class<?> clazz) {
206 // FIXME: Current resolver could be still confused when child node was added by grouping
207 checkArgument(clazz != null);
209 @SuppressWarnings({ "rawtypes", "unchecked" })
210 Class<?> parent = findHierarchicalParent((Class) clazz);
211 if (parent == null) {
212 LOG.debug("Did not find a parent for class {}", clazz);
216 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
217 String parentModelPackage = getModelRootPackageName(parent.getPackage());
219 return !clazzModelPackage.equals(parentModelPackage);
223 * Returns root package name for supplied package.
226 * Package for which find model root package.
227 * @return Package of model root.
229 public static String getModelRootPackageName(final Package pkg) {
230 return getModelRootPackageName(pkg.getName());
234 * Returns root package name for supplied package name.
237 * Package for which find model root package.
238 * @return Package of model root.
240 public static String getModelRootPackageName(final String name) {
241 checkArgument(name != null, "Package name should not be null.");
242 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
243 BindingMapping.PACKAGE_PREFIX, name);
244 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
245 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
246 ROOT_PACKAGE_PATTERN_STRING);
247 return match.group(0);
250 @SuppressWarnings("checkstyle:illegalCatch")
251 public static QNameModule getQNameModule(final Class<?> clz) {
252 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
253 || Action.class.isAssignableFrom(clz)) {
254 return findQName(clz).getModule();
257 return BindingReflections.getModuleInfo(clz).getName().getModule();
258 } catch (Exception e) {
259 throw new IllegalStateException("Unable to get QName of defining model.", e);
264 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
266 * @param cls data object class
267 * @return Instance of {@link YangModuleInfo} associated with model, from
268 * which this class was derived.
270 public static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
271 checkArgument(cls != null);
272 String packageName = getModelRootPackageName(cls.getPackage());
273 final String potentialClassName = getModuleInfoClassName(packageName);
274 return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
275 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
276 return (YangModuleInfo) verifyNotNull(moduleInfoClass.getMethod("getInstance").invoke(null));
280 public static @NonNull String getModuleInfoClassName(final String packageName) {
281 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
285 * Check if supplied class is derived from YANG model.
289 * @return true if class is derived from YANG model.
291 public static boolean isBindingClass(final Class<?> cls) {
292 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
295 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
299 * Checks if supplied method is callback for notifications.
301 * @param method method to check
302 * @return true if method is notification callback.
304 public static boolean isNotificationCallback(final Method method) {
305 checkArgument(method != null);
306 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
307 Class<?> potentialNotification = method.getParameterTypes()[0];
308 if (isNotification(potentialNotification)
309 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
317 * Checks is supplied class is a {@link Notification}.
319 * @param potentialNotification class to examine
320 * @return True if the class represents a Notification.
322 public static boolean isNotification(final Class<?> potentialNotification) {
323 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
324 return Notification.class.isAssignableFrom(potentialNotification);
328 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
329 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
331 * @return Set of {@link YangModuleInfo} available for current classloader.
333 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos() {
334 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
338 * Loads {@link YangModuleInfo} infos available on supplied classloader.
341 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
342 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
343 * {@link YangModuleInfo}.
346 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
347 * collecting results of {@link YangModuleInfo#getImportedModules()}.
350 * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
352 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
353 * @return Set of {@link YangModuleInfo} available for supplied classloader.
355 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
356 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
357 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
359 for (YangModelBindingProvider bindingProvider : serviceLoader) {
360 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
361 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
362 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
364 return moduleInfoSet.build();
368 * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
369 * information does not change. Subsequent accesses may return cached values.
372 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
373 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
374 * {@link YangModuleInfo}.
377 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
378 * collecting results of {@link YangModuleInfo#getImportedModules()}.
380 * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
381 * @return Set of {@link YangModuleInfo} available for supplied classloader.
384 public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
385 return MODULE_INFO_CACHE.getUnchecked(loader);
388 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
389 final Builder<YangModuleInfo> moduleInfoSet) {
390 moduleInfoSet.add(moduleInfo);
391 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
392 collectYangModuleInfo(dependency, moduleInfoSet);
397 * Checks if supplied class represents RPC Input / RPC Output.
400 * Class to be checked
401 * @return true if class represents RPC Input or RPC Output class.
403 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
404 return DataContainer.class.isAssignableFrom(targetType)
405 && !ChildOf.class.isAssignableFrom(targetType)
406 && !Notification.class.isAssignableFrom(targetType)
407 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
411 * Scans supplied class and returns an iterable of all data children classes.
414 * YANG Modeled Entity derived from DataContainer
415 * @return Iterable of all data children, which have YANG modeled entity
417 @SuppressWarnings("unchecked")
418 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
419 checkArgument(type != null, "Target type must not be null");
420 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
421 List<Class<? extends DataObject>> ret = new LinkedList<>();
422 for (Method method : type.getMethods()) {
423 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
424 BindingMapping.GETTER_PREFIX);
425 if (entity.isPresent()) {
426 ret.add((Class<? extends DataObject>) entity.get());
433 * Scans supplied class and returns an iterable of all data children classes.
436 * YANG Modeled Entity derived from DataContainer
437 * @return Iterable of all data children, which have YANG modeled entity
439 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
440 return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
443 private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
444 checkArgument(type != null, "Target type must not be null");
445 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
447 Map<Class<?>, Method> ret = new HashMap<>();
448 for (Method method : type.getMethods()) {
449 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
450 if (entity.isPresent()) {
451 ret.put(entity.get(), method);
458 public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
459 return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
462 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
463 final String prefix) {
464 final String methodName = method.getName();
465 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
466 return Optional.empty();
469 final Class<?> returnType = method.getReturnType();
470 if (DataContainer.class.isAssignableFrom(returnType)) {
471 return optionalDataContainer(returnType);
472 } else if (List.class.isAssignableFrom(returnType)) {
473 return getYangModeledReturnType(method, 0);
474 } else if (Map.class.isAssignableFrom(returnType)) {
475 return getYangModeledReturnType(method, 1);
477 return Optional.empty();
480 @SuppressWarnings("checkstyle:illegalCatch")
481 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
482 final int parameterOffset) {
484 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
485 return genericParameter(method.getGenericReturnType(), parameterOffset).flatMap(
486 result -> result instanceof Class ? optionalCast((Class<?>) result) : Optional.empty());
488 } catch (Exception e) {
490 * It is safe to log this this exception on debug, since this
491 * method should not fail. Only failures are possible if the
494 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
496 return Optional.empty();
499 private static Optional<Class<? extends DataContainer>> optionalCast(final Class<?> type) {
500 return DataContainer.class.isAssignableFrom(type) ? optionalDataContainer(type) : Optional.empty();
503 private static Optional<Class<? extends DataContainer>> optionalDataContainer(final Class<?> type) {
504 return Optional.of(type.asSubclass(DataContainer.class));
507 private static Optional<Type> genericParameter(final Type type, final int offset) {
508 if (type instanceof ParameterizedType) {
509 final Type[] parameters = ((ParameterizedType) type).getActualTypeArguments();
510 if (parameters.length > offset) {
511 return Optional.of(parameters[offset]);
514 return Optional.empty();
517 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
520 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
521 return resolveQNameNoCache(key);
525 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
526 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
527 * {@link #computeQName(Class)} to compute QName for missing types.
529 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
533 field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
534 } catch (NoSuchFieldException e) {
535 LOG.debug("{} does not have a {} field, falling back to computation", key,
536 BindingMapping.QNAME_STATIC_FIELD_NAME, e);
537 return Optional.of(computeQName(key));
540 final Object obj = field.get(null);
541 if (obj instanceof QName) {
542 return Optional.of((QName) obj);
544 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
546 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
547 * possible if the runtime / backing is inconsistent.
549 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
551 return Optional.empty();
555 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
561 * <li>rpc input: local name is "input".
562 * <li>rpc output: local name is "output".
563 * <li>augmentation: local name is "module name".
567 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
570 * @throws IllegalStateException If YangModuleInfo could not be resolved
571 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
573 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
574 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
575 private static QName computeQName(final Class key) {
576 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
578 YangModuleInfo moduleInfo;
580 moduleInfo = getModuleInfo(key);
581 } catch (Exception e) {
582 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
585 final QName module = moduleInfo.getName();
586 if (Augmentation.class.isAssignableFrom(key)) {
588 } else if (isRpcType(key)) {
589 final String className = key.getSimpleName();
590 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
591 return YangConstants.operationOutputQName(module.getModule()).intern();
594 return YangConstants.operationInputQName(module.getModule()).intern();
598 * Fallback for Binding types which do not have QNAME field
605 * Extracts augmentation from Binding DTO field using reflection.
608 * Instance of DataObject which is augmentable and may contain
610 * @return Map of augmentations if read was successful, otherwise empty map.
612 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
613 if (input instanceof AugmentationHolder) {
614 return ((AugmentationHolder) input).augmentations();
616 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
620 * Determines if two augmentation classes or case classes represents same
624 * Two augmentations or cases could be substituted only if and if:
626 * <li>Both implements same interfaces</li>
627 * <li>Both have same children</li>
628 * <li>If augmentations: Both have same augmentation target class. Target
629 * class was generated for data node in grouping.</li>
630 * <li>If cases: Both are from same choice. Choice class was generated for
631 * data node in grouping.</li>
635 * <b>Explanation:</b> Binding Specification reuses classes generated for
636 * groupings as part of normal data tree, this classes from grouping could
637 * be used at various locations and user may not be aware of it and may use
638 * incorrect case or augmentation in particular subtree (via copy
639 * constructors, etc).
642 * Class which is potential substitution
644 * Class which should be used at particular subtree
645 * @return true if and only if classes represents same data.
647 @SuppressWarnings({ "rawtypes", "unchecked" })
648 public static boolean isSubstitutionFor(final Class potential, final Class target) {
649 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
650 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
651 if (!subImplemented.equals(targetImplemented)) {
654 if (Augmentation.class.isAssignableFrom(potential)
655 && !BindingReflections.findAugmentationTarget(potential).equals(
656 BindingReflections.findAugmentationTarget(target))) {
659 for (Method potentialMethod : potential.getMethods()) {
661 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
662 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
665 } catch (NoSuchMethodException e) {
666 // Counterpart method is missing, so classes could not be substituted.
668 } catch (SecurityException e) {
669 throw new IllegalStateException("Could not compare methods", e);