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