View Javadoc
1   /*
2    * Copyright (c) 2006 JMockit developers
3    * This file is subject to the terms of the MIT license (see LICENSE.txt).
4    */
5   package mockit.internal.reflection;
6   
7   import static mockit.internal.reflection.ParameterReflection.NO_PARAMETERS;
8   
9   import edu.umd.cs.findbugs.annotations.NonNull;
10  import edu.umd.cs.findbugs.annotations.Nullable;
11  
12  import java.lang.reflect.InvocationTargetException;
13  import java.lang.reflect.Method;
14  
15  public final class AnnotationReflection {
16      private AnnotationReflection() {
17      }
18  
19      @NonNull
20      public static String readAnnotationAttribute(@NonNull Object annotationInstance, @NonNull String attributeName) {
21          try {
22              return readAttribute(annotationInstance, attributeName);
23          } catch (NoSuchMethodException e) {
24              throw new RuntimeException(e);
25          }
26      }
27  
28      @Nullable
29      public static String readAnnotationAttributeIfAvailable(@NonNull Object annotationInstance,
30              @NonNull String attributeName) {
31          try {
32              return readAttribute(annotationInstance, attributeName);
33          } catch (NoSuchMethodException e) {
34              return null;
35          }
36      }
37  
38      @NonNull
39      private static String readAttribute(@NonNull Object annotationInstance, @NonNull String attributeName)
40              throws NoSuchMethodException {
41          try {
42              Method publicMethod = annotationInstance.getClass().getMethod(attributeName, NO_PARAMETERS);
43              return (String) publicMethod.invoke(annotationInstance);
44          } catch (IllegalAccessException e) {
45              throw new RuntimeException(e);
46          } catch (InvocationTargetException e) {
47              throw new RuntimeException(e.getCause());
48          }
49      }
50  }