Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Default Element Value from Annotation in Java

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.

  • Is it possible to get the default value of an element within an annotation?
  • If so, how?

Also, I know I could hard code this value, however I would like to make the program slightly more robust.

like image 452
Kevin Bowersox Avatar asked Nov 10 '12 17:11

Kevin Bowersox


2 Answers

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";
  }
}
like image 167
FThompson Avatar answered Oct 21 '22 15:10

FThompson


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();
}
like image 1
Biju Kunjummen Avatar answered Oct 21 '22 15:10

Biju Kunjummen