[英]How to call a method without repeat from other methods in java
例如,我有成千上万的方法,如:
AA() {
...
}
BB() {
...
}
CC() {
...
}
etc ...
现在我想在每个方法的开头调用一个方法printCurrentMethodName()。 那意味着,
AA() {
printCurrentMethodName();
...
}
BB() {
printCurrentMethodName();
...
}
CC() {
printCurrentMethodName();
...
}
etc ...
包括printCurrentMethodName()在数千种方法的开始是耗时的。
有没有什么方法可以在每个方法的开头调用printCurrentMethodName()而不在那些数千个方法中重复它?
(我不能使用@Before或@BeforeMethod注释之类的东西,因为它会在输入AA()之前调用printCurrentMethodName(),因此它不会按预期打印方法名称)
如果您只想打印测试方法的名称,那么您可以创建一个类似于TestName规则的JUnit 规则
public class PrintTestName extends TestWatcher {
@Override
protected void starting(Description d) {
System.out.println(d.getMethodName());
}
}
并在测试中使用它
public class YourTest {
@Rule
public final PrintTestName printTestName = new PrintTestName();
@Test
public AA() {
...
}
...
您可以使用java.lang.reflect.InvocationHandler
来实现此目的。
在调用类中的任何方法( AA
, BB
, CC
等)之前, invoke
InvocationHandler
的invoke
方法。 在invoke
方法中,您可以访问被调用的实际方法,并且可以在调用实际方法之前或之后添加其他逻辑,例如打印被调用方法的名称。
代码示例:
public class PrintClassName {
public static void main(String[] a) {
Service srv = (Service) Proxy.newProxyInstance(
PrintClassName.class.getClassLoader(),
new Class<?>[]{Service.class},
new PrintingMethodNameHandler(new ServiceImpl())
);
srv.doNothing();
}
}
interface Service {
void doNothing();
}
class ServiceImpl implements Service {
public void doNothing() { }
}
class PrintingMethodNameHandler implements InvocationHandler {
private Service service;
public PrintingMethodNameHandler(final Service service) {
this.service = service;
}
@Override
public Object invoke(final Object proxy, final Method method,
final Object[] args) throws Throwable {
System.out.println(method.getName());
return method.invoke(service, args);
}
}
您可以使用正则表达式在每个函数上插入此调用。
用$1\\nprintCurrentMethodName();
替换(\\w+\\(\\w*\\)\\s*\\{)
$1\\nprintCurrentMethodName();
如何使用AspectJ注释。
对于前
常见的AspectJ注释:1。@ Before - 在方法执行之前运行
2. @ After - 在方法返回结果后运行
3. @ AfterReturning - 在方法返回结果后运行,也拦截返回的结果。
4. @ AfterThrowing - 在方法抛出异常后运行
5. @ Around - 运行方法执行,结合上面的所有三个建议。
这可以解决您的问题。 您可以使用它在返回时调用方法,
您可以按照本教程操作。
这很简单,把这一行放在你的方法中。
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.