gpt4 book ai didi

java - java中如何通过反射获取注解

转载 作者:行者123 更新时间:2023-12-04 05:02:38 24 4
gpt4 key购买 nike

这是我的注释:

@RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")

现在我想获取请求方法 it is POST在这种情况下,值 it is /trade/createrequisition在这种情况下。

如何在java中使用反射来做到这一点。

请帮我解决这个问题。

编辑:

这是我的实际方法:
@PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
@RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
public @ResponseBody
void createRequisition(@RequestBody CreateRequisitionRO[] request,
@RequestHeader("validateOnly") boolean validateOnly) {
....
}

这就是我尝试获取@RequestiMapping 的方式:
package com.hexgen.reflection;

import java.lang.reflect.Method;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.hexgen.api.facade.HexgenWebAPI;

public class WebAPITest {
public static void main(String[] args) {
try {
Class<HexgenWebAPI> clazz = HexgenWebAPI.class;
Method methodAnnotaion = clazz.getMethod("createRequisition");
RequestMapping methodRequestMappingAnnotation = methodAnnotaion.getAnnotation(RequestMapping.class);
RequestMethod[] methods = methodRequestMappingAnnotation.method();
String[] mappingValues = methodRequestMappingAnnotation.value();

for(RequestMethod req : methods){
System.out.println("RequestMethod : " + req);
}

for (String string : mappingValues) {
System.out.println("mappingValues : " + string);
}

} catch (Exception e) {
e.printStackTrace();
}

}
}

但我得到这个异常(exception):
java.lang.NoSuchMethodException: com.hexgen.api.facade.HexgenWebAPI.createRequisition()
at java.lang.Class.getMethod(Class.java:1605)
at com.hexgen.reflection.WebAPITest.main(WebAPITest.java:12)

最佳答案

当您尝试获取 RequestMapping 时注解,它可以放在一个类或一个方法上,见下面两种用法:

对于一个类(class) YourClass :

Class<YourClass> clazz = YourClass.class;
RequestMapping clazzRequestMappingAnnotation = clazz.getAnnotation(RequestMapping.class);
RequestMethod[] methods = clazzRequestMappingAnnotation.method();
String[] mappingValues = clazzRequestMappingAnnotation.value();

对于方法 methodName在类 YourClass :
Class<YourClass> clazz = YourClass.class;
Method method = clazz.getMethod("methodName");
RequestMapping methodRequestMappingAnnotation = method.getAnnotation(RequestMapping.class);
RequestMethod[] methods = methodRequestMappingAnnotation.method();
String[] mappingValues = methodRequestMappingAnnotation.value();

关于java - java中如何通过反射获取注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15963055/

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