我尝试获取接口(interface)方法中方法参数User user
上注释@WebParam 的名称“best_user”
。因为它是一个接口(interface),所以以下代码不允许我访问注释:
String methodName = "doSomething";
Class<?> clazz = Class.forName(packageName + "." + "UserService");
Method serviceMethod = null;
for (Method method: clazz.getMethods())
{
if (method.getName().equals(methodName))
{
serviceMethod = method;
break;
}
}
Class<?>[] parameterTypes = serviceMethod.getParameterTypes();
WebParam webParam = parameterTypes[0].getAnnotation(WebParam.class); //webParam is null
String parameterName = webParam.name();
但是 Web 服务框架能够获取此数据。我也能做到吗?
界面:
@WebService(name = "UserService", targetNamespace = "my.targetNamespace")
public interface UserService {
@WebMethod
public String doSomething
(
@WebParam(name = "best_user")
User user
)
}
最佳答案
这不是接口(interface)类型的限制。
Method#getParameterTypes()
返回参数类型的数组。在您的示例中,它仅包含一个 User.class
,因为您的方法有一个 User
类型的参数。
您需要使用Method#getParameterAnnotations()
并获取第一个参数的第一个注释。
Annotation[][] parameterTypes = serviceMethod.getParameterAnnotations();
WebParam webParam = (WebParam) parameterTypes[0][0];
从 Java 8 开始,您还可以使用 Method#getParameters()
和Parameter#getAnnotation()
WebParam webParam = serviceMethod.getParameters()[0].getAnnotation(WebParam.class);
关于java - 接口(interface)方法的参数上的 @WebParam - 如何获取名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997585/