Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Java Annotation not to run a method

I've got a method in my class only for testing purpose :

private void printOut(String msg, Object value)
{
    System.out.println(msg + value);
}

It is a wrapper method for System.out.println();

So I hope, with the use of Annotation, I can choose not to run this method during productive environment while still keep those diagnostic output ready if I am to switch back to debugging environment.

Which Annotation shall I put on top of the method name?

like image 730
Michael Mao Avatar asked Dec 30 '25 07:12

Michael Mao


2 Answers

As I stated above you should use logging. Here are some of the benefits of using logging in an application:

  • Logging can generate detailed information about the operation of an application.
  • Once added to an application, logging requires no human intervention.
  • Application logs can be saved and studied at a later time.
  • If sufficiently detailed and properly formatted, application logs can provide audit trails.
  • By capturing errors that may not be reported to users, logging can help support staff with troubleshooting.
  • By capturing very detailed and programmer-specified messages, logging can help programmers with debugging.
  • Logging can be a debugging tool where debuggers are not available, which is often the case with multi-threaded or distributed applications.
  • Logging stays with the application and can be used anytime the application is run.

Read more about logging here

There are a lot of logging frameworks in java:

  1. Log4j
  2. java.util.logging
  3. Logback.

And several facades, which provides abstraction for various logging frameworks:

  1. slf4j
  2. commons-logging
like image 140
uthark Avatar answered Jan 02 '26 02:01

uthark


One solution is to use AspectJ to do this, as you can control the behavior based on annotations.

Here is a tutorial on how to use annotations as join points:

http://www.eclipse.org/aspectj//doc/next/adk15notebook/annotations-pointcuts-and-advice.html

What you could do is to have:

@DebugMessage
private void printOut(String msg, Object value)
{ }

Then, in your aspect you could have the aspect do the println call.

This way, in production, the aspect isn't included, but, should you ever need to have this active, then just add the aspect, even to production code, to get some debugging.

like image 32
James Black Avatar answered Jan 02 '26 03:01

James Black