How to call a method without repeating from other methods in java

For example, I have thousands of methods like:

AA() {
    ...
}  
BB() {
    ...
}  
CC() {
    ...
}  
etc ...

Now I want to call the printCurrentMethodName () method at the beginning of each method. It means that

AA() {
    printCurrentMethodName();
    ...
}  
BB() {
    printCurrentMethodName();
    ...
}  
CC() {
    printCurrentMethodName();
    ...
}  
etc ...

Including printCurrentMethodName () at the beginning of thousands of methods takes a lot of time.

Is there a way I can call printCurrentMethodName () at the beginning of each method without repeating it in those thousands of methods?

(I cannot use something like @Before or @BeforeMethod annotation because it will call printCurrentMethodName () before entering AA (), and therefore it will not print the method name as expected)

+4
source share
5 answers

, JUnit, TestName

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() {
    ...
  }

  ...
+3

java.lang.reflect.InvocationHandler .

(AA, BB, CC ..) invoke InvocationHandler. 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);
    }
}
+2

.

(\w+\(\w*\)\s*\{) $1\nprintCurrentMethodName();

+1

AspectJ.

ex -

AspectJ: 1. @Before -

2. @ - ,

3. @AfterReturning - , , .

4. @AfterThrowing - ,

5. @Around - , .

. ,

.

0

, .

System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
-1

All Articles