Move BindingReflections to mdsal-binding-spec-util
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / util / BindingReflections.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.binding.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.base.Optional;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
19 import com.google.common.collect.Sets;
20 import 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.ServiceLoader;
30 import java.util.concurrent.TimeUnit;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import javax.annotation.RegEx;
34 import org.opendaylight.yangtools.util.ClassLoaderUtils;
35 import org.opendaylight.yangtools.yang.binding.Action;
36 import org.opendaylight.yangtools.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
39 import org.opendaylight.yangtools.yang.binding.BindingMapping;
40 import org.opendaylight.yangtools.yang.binding.ChildOf;
41 import org.opendaylight.yangtools.yang.binding.DataContainer;
42 import org.opendaylight.yangtools.yang.binding.DataObject;
43 import org.opendaylight.yangtools.yang.binding.Notification;
44 import org.opendaylight.yangtools.yang.binding.RpcService;
45 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
46 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.QNameModule;
49 import org.opendaylight.yangtools.yang.common.YangConstants;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 @Deprecated
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).orNull();
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.getParameterTypes().length <= 2;
141     }
142
143     /**
144      * Extracts Output class for RPC method.
145      *
146      * @param targetMethod
147      *            method to scan
148      * @return Optional.absent() 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.absent();
160     }
161
162     /**
163      * Extracts input class for RPC method.
164      *
165      * @param targetMethod
166      *            method to scan
167      * @return Optional.absent() 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.absent();
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      * Extract a QNameModule from YangModuleInfo.
246      *
247      * @param modInfo Module info
248      * @return QNameModule for the module
249      * @throws NullPointerException in modInfo is null
250      *
251      * @deprecated Use {@code YangModuleInfo.getName().getModule()} instead.
252      */
253     @Deprecated
254     public static QNameModule getQNameModule(final YangModuleInfo modInfo) {
255         return modInfo.getName().getModule();
256     }
257
258     /**
259      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
260      *
261      * @param cls data object class
262      * @return Instance of {@link YangModuleInfo} associated with model, from
263      *         which this class was derived.
264      */
265     public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
266         checkArgument(cls != null);
267         String packageName = getModelRootPackageName(cls.getPackage());
268         final String potentialClassName = getModuleInfoClassName(packageName);
269         return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
270             Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
271             return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
272         });
273     }
274
275     public static String getModuleInfoClassName(final String packageName) {
276         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
277     }
278
279     /**
280      * Check if supplied class is derived from YANG model.
281      *
282      * @param cls
283      *            Class to check
284      * @return true if class is derived from YANG model.
285      */
286     public static boolean isBindingClass(final Class<?> cls) {
287         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
288             return true;
289         }
290         return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
291     }
292
293     /**
294      * Checks if supplied method is callback for notifications.
295      *
296      * @param method method to check
297      * @return true if method is notification callback.
298      */
299     public static boolean isNotificationCallback(final Method method) {
300         checkArgument(method != null);
301         if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) {
302             Class<?> potentialNotification = method.getParameterTypes()[0];
303             if (isNotification(potentialNotification)
304                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
305                 return true;
306             }
307         }
308         return false;
309     }
310
311     /**
312      * Checks is supplied class is a {@link Notification}.
313      *
314      * @param potentialNotification class to examine
315      * @return True if the class represents a Notification.
316      */
317     public static boolean isNotification(final Class<?> potentialNotification) {
318         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
319         return Notification.class.isAssignableFrom(potentialNotification);
320     }
321
322     /**
323      * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
324      * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
325      *
326      * @return Set of {@link YangModuleInfo} available for current classloader.
327      */
328     public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
329         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
330     }
331
332     /**
333      * Loads {@link YangModuleInfo} infos available on supplied classloader.
334      *
335      * <p>
336      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
337      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
338      * {@link YangModuleInfo}.
339      *
340      * <p>
341      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
342      * collecting results of {@link YangModuleInfo#getImportedModules()}.
343      *
344      * @param loader
345      *            Classloader for which {@link YangModuleInfo} should be
346      *            retrieved.
347      * @return Set of {@link YangModuleInfo} available for supplied classloader.
348      */
349     public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
350         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
351         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
352                 loader);
353         for (YangModelBindingProvider bindingProvider : serviceLoader) {
354             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
355             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
356             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
357         }
358         return moduleInfoSet.build();
359     }
360
361     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
362             final Builder<YangModuleInfo> moduleInfoSet) {
363         moduleInfoSet.add(moduleInfo);
364         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
365             collectYangModuleInfo(dependency, moduleInfoSet);
366         }
367     }
368
369     /**
370      * Checks if supplied class represents RPC Input / RPC Output.
371      *
372      * @param targetType
373      *            Class to be checked
374      * @return true if class represents RPC Input or RPC Output class.
375      */
376     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
377         return DataContainer.class.isAssignableFrom(targetType)
378                 && !ChildOf.class.isAssignableFrom(targetType)
379                 && !Notification.class.isAssignableFrom(targetType)
380                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
381     }
382
383     /**
384      * Scans supplied class and returns an iterable of all data children classes.
385      *
386      * @param type
387      *            YANG Modeled Entity derived from DataContainer
388      * @return Iterable of all data children, which have YANG modeled entity
389      */
390     @SuppressWarnings("unchecked")
391     public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
392         checkArgument(type != null, "Target type must not be null");
393         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
394         List<Class<? extends DataObject>> ret = new LinkedList<>();
395         for (Method method : type.getMethods()) {
396             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
397             if (entity.isPresent()) {
398                 ret.add((Class<? extends DataObject>) entity.get());
399             }
400         }
401         return ret;
402     }
403
404     /**
405      * Scans supplied class and returns an iterable of all data children classes.
406      *
407      * @param type
408      *            YANG Modeled Entity derived from DataContainer
409      * @return Iterable of all data children, which have YANG modeled entity
410      */
411     public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
412         checkArgument(type != null, "Target type must not be null");
413         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
414             type);
415         Map<Class<?>, Method> ret = new HashMap<>();
416         for (Method method : type.getMethods()) {
417             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
418             if (entity.isPresent()) {
419                 ret.put(entity.get(), method);
420             }
421         }
422         return ret;
423     }
424
425     @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
426     private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
427         if ("getClass".equals(method.getName()) || !method.getName().startsWith("get")
428                 || method.getParameterTypes().length > 0) {
429             return Optional.absent();
430         }
431
432         Class returnType = method.getReturnType();
433         if (DataContainer.class.isAssignableFrom(returnType)) {
434             return Optional.of(returnType);
435         } else if (List.class.isAssignableFrom(returnType)) {
436             try {
437                 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
438                     Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
439                     if (listResult instanceof Class
440                             && DataContainer.class.isAssignableFrom((Class) listResult)) {
441                         return Optional.of((Class) listResult);
442                     }
443                     return Optional.absent();
444                 });
445             } catch (Exception e) {
446                 /*
447                  * It is safe to log this this exception on debug, since this
448                  * method should not fail. Only failures are possible if the
449                  * runtime / backing.
450                  */
451                 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
452             }
453         }
454         return Optional.absent();
455     }
456
457     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
458
459         @Override
460         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
461             return resolveQNameNoCache(key);
462         }
463
464         /**
465          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
466          * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
467          * {@link #computeQName(Class)} to compute QName for missing types.
468          */
469         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
470             try {
471                 final Field field;
472                 try {
473                     field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
474                 } catch (NoSuchFieldException e) {
475                     LOG.debug("{} does not have a {} field, falling back to computation", key,
476                         BindingMapping.QNAME_STATIC_FIELD_NAME, e);
477                     return Optional.of(computeQName(key));
478                 }
479
480                 final Object obj = field.get(null);
481                 if (obj instanceof QName) {
482                     return Optional.of((QName) obj);
483                 }
484             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
485                 /*
486                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
487                  * possible if the runtime / backing is inconsistent.
488                  */
489                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
490             }
491             return Optional.absent();
492         }
493
494         /**
495          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
496          * supplied class.
497          *
498          * <p>
499          * If class is
500          * <ul>
501          * <li>rpc input: local name is "input".
502          * <li>rpc output: local name is "output".
503          * <li>augmentation: local name is "module name".
504          * </ul>
505          *
506          * <p>
507          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
508          * QName.
509          *
510          * @throws IllegalStateException If YangModuleInfo could not be resolved
511          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
512          */
513         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
514         @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
515         private static QName computeQName(final Class key) {
516             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
517
518             YangModuleInfo moduleInfo;
519             try {
520                 moduleInfo = getModuleInfo(key);
521             } catch (Exception e) {
522                 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
523                     e);
524             }
525             final QName module = moduleInfo.getName();
526             if (Augmentation.class.isAssignableFrom(key)) {
527                 return module;
528             } else if (isRpcType(key)) {
529                 final String className = key.getSimpleName();
530                 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
531                     return YangConstants.operationOutputQName(module.getModule()).intern();
532                 }
533
534                 return YangConstants.operationInputQName(module.getModule()).intern();
535             }
536
537             /*
538              * Fallback for Binding types which do not have QNAME field
539              */
540             return module;
541         }
542     }
543
544     /**
545      * Given a {@link YangModuleInfo}, create a QName representing it. The QName is formed by reusing the module's
546      * namespace and revision using the module's name as the QName's local name.
547      *
548      * @param moduleInfo
549      *            module information
550      * @return QName representing the module
551      *
552      * @deprecated Use {@link YangModuleInfo#getName()} instead.
553      */
554     @Deprecated
555     public static QName getModuleQName(final YangModuleInfo moduleInfo) {
556         checkArgument(moduleInfo != null, "moduleInfo must not be null.");
557         return moduleInfo.getName();
558     }
559
560     /**
561      * Extracts augmentation from Binding DTO field using reflection.
562      *
563      * @param input
564      *            Instance of DataObject which is augmentable and may contain
565      *            augmentation
566      * @return Map of augmentations if read was successful, otherwise empty map.
567      */
568     public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
569         return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
570     }
571
572     /**
573      * Determines if two augmentation classes or case classes represents same
574      * data.
575      *
576      * <p>
577      * Two augmentations or cases could be substituted only if and if:
578      * <ul>
579      * <li>Both implements same interfaces</li>
580      * <li>Both have same children</li>
581      * <li>If augmentations: Both have same augmentation target class. Target
582      * class was generated for data node in grouping.</li>
583      * <li>If cases: Both are from same choice. Choice class was generated for
584      * data node in grouping.</li>
585      * </ul>
586      *
587      * <p>
588      * <b>Explanation:</b> Binding Specification reuses classes generated for
589      * groupings as part of normal data tree, this classes from grouping could
590      * be used at various locations and user may not be aware of it and may use
591      * incorrect case or augmentation in particular subtree (via copy
592      * constructors, etc).
593      *
594      * @param potential
595      *            Class which is potential substitution
596      * @param target
597      *            Class which should be used at particular subtree
598      * @return true if and only if classes represents same data.
599      */
600     @SuppressWarnings({ "rawtypes", "unchecked" })
601     public static boolean isSubstitutionFor(final Class potential, final Class target) {
602         HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
603         HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
604         if (!subImplemented.equals(targetImplemented)) {
605             return false;
606         }
607         if (Augmentation.class.isAssignableFrom(potential)
608                 && !BindingReflections.findAugmentationTarget(potential).equals(
609                         BindingReflections.findAugmentationTarget(target))) {
610             return false;
611         }
612         for (Method potentialMethod : potential.getMethods()) {
613             try {
614                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
615                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
616                     return false;
617                 }
618             } catch (NoSuchMethodException e) {
619                 // Counterpart method is missing, so classes could not be substituted.
620                 return false;
621             } catch (SecurityException e) {
622                 throw new IllegalStateException("Could not compare methods", e);
623             }
624         }
625         return true;
626     }
627 }