如何检查如果当前方法的一个参数具有一个注释和检索Java中该参数值? [英] How to check if a parameter of the current method has an annotation and retrieve that parameter value in Java?
问题描述
考虑这个code:
public example(String s, int i, @Foo Bar bar) {
/* ... */
}
我要检查,如果该方法有一个注释 @foo
并获得参数或抛出一个异常,如果没有 @foo
注释中找到。
I want to check if the method has an annotation @Foo
and get the argument or throw an exception if no @Foo
annotation is found.
我目前的做法是,先获取当前方法,然后通过参数注解迭代:
My current approach is to first get the current method and then iterate through the parameter annotations:
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
class Util {
private Method getCurrentMethod() {
try {
final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
final StackTraceElement ste = stes[stes.length - 1];
final String methodName = ste.getMethodName();
final String className = ste.getClassName();
final Class<?> currentClass = Class.forName(className);
return currentClass.getDeclaredMethod(methodName);
} catch (Exception cause) {
throw new UnsupportedOperationException(cause);
}
}
private Object getArgumentFromMethodWithAnnotation(Method method, Class<?> annotation) {
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : paramAnnotations) {
for (Annotation an : annotations) {
/* ... */
}
}
}
}
这是正确的做法还是有一个更好的?
将如何forach循环中的code是什么样子?我不知道我是否已经明白了什么 getParameterAnnotations
实际上返回...
Is this the right approach or is there a better one?
How would the code inside the forach loop look like? I'm not sure if I have understood the what getParameterAnnotations
actually returns...
推荐答案
for循环外
for (Annotation[] annotations : paramAnnotations) {
...
}
应该使用一个明确的反击,否则你不知道你现在正在处理哪些参数权
should use an explicit counter, otherwise you don't know what parameter you are processing right now
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
final Class[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramAnnotations.length; i++) {
for (Annotation a: paramAnnotations[i]) {
if (a instanceof Foo) {
System.out.println(String.format("parameter %d with type %s is annotated with @Foo", i, paramTypes[i]);
}
}
}
另外,还要确保你的注释类型都标注有 @Retention(RetentionPolicy.RUNTIME)
从你的问题是不完全清楚你正在尝试做的。我们同意正式参数与实际参数的区别:
From your question it is not entirely clear what you are trying to do. We agree on the difference of formal parameters vs. actual arguments:
void foo(int x) { }
{ foo(3); }
其中, X
是一个参数, 3
一种说法?
where x
is a parameter and 3
is an argument?
这是不可能通过反射来获取的方法的参数。如果它是在所有可能的,你将不得不使用 sun.unsafe
包。我不能告诉你很多关于这虽然。
It is not possible to get the arguments of methods via reflection. If it is possible at all, you would have to use the sun.unsafe
package. I can't tell you much about that though.
这篇关于如何检查如果当前方法的一个参数具有一个注释和检索Java中该参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!