gpt4 book ai didi

java - 如果参数注解存在则获取参数值

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:48 24 4
gpt4 key购买 nike

如果参数上存在注释,是否可以获取参数的值?

给定带有参数级注释的 EJB:

public void fooBar(@Foo String a, String b, @Foo String c) {...}

拦截器:

@AroundInvoke
public Object doIntercept(InvocationContext context) throws Exception {
// Get value of parameters that have annotation @Foo
}

最佳答案

在您的doIntercept() 中,您可以检索从InvocationContext 调用的方法并获得parameter annotations。 .

Method method = context.getMethod();
Annotation[][] annotations = method.getParameterAnnotations();
// iterate through annotations and check
Object[] parameterValues = context.getParameters();

// check if annotation exists at each index
if (annotation[0].length > 0 /* and if the annotation is the type you want */ )
// get the value of the parameter
System.out.println(parameterValues[0]);

因为如果没有注释,Annotation[][] 返回一个空的二维数组,您知道哪些参数位置有注释。然后您可以调用 InvocationContext#getParameters()获取包含所有传递参数值的 Object[]。该数组的大小与 Annotation[][] 相同。只返回没有注释的索引值。

关于java - 如果参数注解存在则获取参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18129300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com