I have created my own annotation, which I utilize via reflection to make a decision in my code. The annotation has a default value set for its sole element. Is there a way I can access the default value via reflection?
PageableRequestMapping.java (Annotation)
package org.tothought.controllers.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface PageableRequestMapping {
    String variablePath() default "/";
}
Psuedo Code to Retrieve Default Value
private int parsePageNumber(StringBuffer requestURL,
        PageableRequestMapping pageableRequestMapping) {
        String variablePath = pageableRequestMapping.variablePath();
    //Psuedo code doesn't work in Java, included to illustrate intentions   
        if(variablePath.equalsIgnoreCase(pageableRequestMapping.variablePath().default())){
           //handle default case    
        }else{
          //handle different case
        }
        return 0;
}
My research of the issue has turned up no examples. I theorized this value could be accessed in a static manner through the class, but it cannot. So I am left with two questions.
Also, I know I could hard code this value, however I would like to make the program slightly more robust.
You can use reflection to get the Method object, and then utilize Method#getDefaultValue().
Method method = pageableReqMapping.annotationType().getMethod("variablePath");
String variablePath = (String) method.getDefaultValue();
Here's a concrete example:
public class AnnotationTest {
  public static void main(String[] args) throws Exception {
    Class<?> clazz = Annotation.class;
    Method method = clazz.getDeclaredMethod("value");
    String value = (String) method.getDefaultValue();
    System.out.println(value);
  }
  public @interface Annotation {
    String value() default "default value";
  }
}
                        You can do it this way, by applying your annotation on a class and retrieving it from the class via reflection:
@PageableRequestMapping
class MyUtilClass{
}
public String getDefaultValue(){
    PageableRequestMapping pageableRequestMapping = MyUtilClass.class.getAnnotation(PageableRequestMapping.class);
    return pageableRequestMapping.variablePath();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With