Kev*_*sox 19 java reflection annotations
我创建了自己的注释,我通过反射在我的代码中做出决定.注释具有为其唯一元素设置的默认值.有没有办法可以通过反射访问默认值?
PageableRequestMapping.java(注释)
package org.tothought.controllers.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface PageableRequestMapping {
String variablePath() default "/";
}
Run Code Online (Sandbox Code Playgroud)
Psuedo代码检索默认值
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;
}
Run Code Online (Sandbox Code Playgroud)
我对这个问题的研究没有任何例子.我理论上这个值可以通过类以静态方式访问,但它不能.所以我有两个问题.
此外,我知道我可以硬编码这个值,但是我想让程序稍微强一些.
FTh*_*son 22
您可以使用反射来获取Method对象,然后使用Method#getDefaultValue().
Method method = pageableReqMapping.annotationType().getMethod("variablePath");
String variablePath = (String) method.getDefaultValue();
Run Code Online (Sandbox Code Playgroud)
这是一个具体的例子:
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";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7944 次 |
| 最近记录: |