[英]Java - Dynamically make transactional methods ignored
I'm writing a program which talks to a SOAP API. 我正在编写一个与SOAP API通讯的程序。 The program I'm writing deals with money, and it would be useful to be able to determine at run time (my reasoning being that if I can deal with it at run time I can easily put together configuration files for use post-compilation) whether or not I want the methods which deal with money to be executed. 我正在编写的程序需要花钱,并且能够在运行时确定(我的理由是,如果我可以在运行时进行处理,则可以轻松地将配置文件放在一起以便在编译后使用)我是否想要执行处理金钱的方法。
I have a make request method which all API calls go through, ideally I would like something like so: 我有一个make请求方法,所有API调用都会通过该方法,理想情况下,我希望这样:
...
@DealsWithMoney
public void myMethodWhichMakesAnAPIRequest() {
...
this.makeRequest(...);
}
public void makeRequest(...) {
if (!this.allowMoneyHandlingMethods) {
//Psuedo code
if (method_that_called_this_method has @DealsWithMoney annotation) {
//ignore
}
}
}
I've never written a custom annotation, so I would appreciate some guidance here. 我从未编写过自定义注释,因此希望在此提供一些指导。 Also, if you could suggest a better method for handling this? 另外,如果您可以提出更好的方法来解决此问题?
Cheers, 干杯,
Pete 皮特
public @interface DealsWithMoney {}
will define the annotation for you. 将为您定义注释。
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
gets the stack track from which you should be able to get the Method
or Member
reference of the caller and do 获取堆栈跟踪,您应该可以从该跟踪获得调用方的Method
或Member
引用并执行
Annotation[] annotations = method.getDeclaredAnnotations();
and check to see if the annotation you are looking for is in the returned list. 并检查您要查找的注释是否在返回列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.