访问构造的注解参数进行修改
Accessing Annotation's Parameter ot Construction for Modification
我对注释的确切工作方式有点困惑,所以我无法轻易找到这个问题的答案,即使它就在我眼前,没有任何解释。
举个例子,我们有这个 class
//this happens to be a Spring annotation in this case
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = " not found")
class NotFoundException extends RuntimeException {
public NotFoundException(String resourceName) {
//get access to reason from class's annotation
reason = resourceName + reason;
}
}
如何在运行时访问注释的参数 reason
?这可能吗?如果是这样,我知道涉及反射,但不完全确定正确的方法。
您可以通过以下方式阅读注释的 reason
:
String reason = NotFoundException.class.getAnnotation(ResponseStatus.class).reason();
您不能更改注释中的值。
向您展示了从注释中检索属性的技术方法。
但是我认为没有理由这样做。其一,正如 ResponseStatus#reason
的 javadoc 所述
If this element is not set, it will default to the standard status
message for the status code. Note that due to the use of
HttpServletResponse.sendError(int, String)
, the response will be
considered complete and should not be written to any further.
您可能希望将标准状态消息写入响应而不是您自己的响应。
如果您仍然想要自己的,我会定义一个常量表达式并在您需要 reason
时引用它,而不是从注释中检索它。
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = NotFoundException.REASON)
class NotFoundException extends RuntimeException {
static final String REASON = " not found"; // you can define this in another class
public NotFoundException(String resourceName) {
String something = resourceName + REASON;
}
}
我对注释的确切工作方式有点困惑,所以我无法轻易找到这个问题的答案,即使它就在我眼前,没有任何解释。
举个例子,我们有这个 class
//this happens to be a Spring annotation in this case
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = " not found")
class NotFoundException extends RuntimeException {
public NotFoundException(String resourceName) {
//get access to reason from class's annotation
reason = resourceName + reason;
}
}
如何在运行时访问注释的参数 reason
?这可能吗?如果是这样,我知道涉及反射,但不完全确定正确的方法。
您可以通过以下方式阅读注释的 reason
:
String reason = NotFoundException.class.getAnnotation(ResponseStatus.class).reason();
您不能更改注释中的值。
但是我认为没有理由这样做。其一,正如 ResponseStatus#reason
的 javadoc 所述
If this element is not set, it will default to the standard status message for the status code. Note that due to the use of
HttpServletResponse.sendError(int, String)
, the response will be considered complete and should not be written to any further.
您可能希望将标准状态消息写入响应而不是您自己的响应。
如果您仍然想要自己的,我会定义一个常量表达式并在您需要 reason
时引用它,而不是从注释中检索它。
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = NotFoundException.REASON)
class NotFoundException extends RuntimeException {
static final String REASON = " not found"; // you can define this in another class
public NotFoundException(String resourceName) {
String something = resourceName + REASON;
}
}