how to implement macros in java
I need to be able to print in production to logger, but while developing i would like t开发者_StackOverflow中文版o print to the console. So in c++ i would simply use a macro for it, and that would be a change of 1 line, how can i do that in java? Thanks
Macros aren't the right answer, using a good logging framework is. Look at SLF4J (or the older log4j). If you route all your logging calls through one of these facades, you'll be able to send your logged messages to the console, or a file, or any other appender that you like with a tiny bit of config.
Java doesn't have C/C++-like macros, and so there's no easy way to automatically disable all of your logging code. What you can do is something like this:
public class Utility {
private Utility() {} // Singleton
public static void log(String toLog) {
System.out.println(toLog);
}
/* ... etc. ... */
}
Now, anywhere in your program that you want to log an event, you can just call
Utility.log("Here's a message!");
In production builds, you can silence this output by just changing the implementation of log
to be a no-op.
This is not as efficient as the C/C++-ism of just having your logging macro expand to nothingness at compile-time, but a good optimizer/JIT should be able to notice that the argument isn't getting used and optimize away the logic to set up those arguments.
Look at http://logging.apache.org/log4j/index.html or http://www.slf4j.org/download.html
Just define a static method and call it. In that method put a constant which is set to true
when you're debugging and execute different code depending on whether you are debugging or not.
In general, write a function that reads a system property to know where to print to.
Or, for this specific case, use log4j that allows you to specify stuff like this in a config file.
Java does not directly support a preprocessor and hence does not support macros.
Logging, however, is a common need so there are several options to choose from. At the moment the best approach is to use slf4j (as the {}-constructs allow for good code), with a suitable backend. For starters the "slf4j-simple" backend in the slf4j distribution is nice.
Note that the slf4j author strongly favors the logback backend. For now, you do not need that.
My answer is a bit late - 4 years! :)
But just for the record, if you must use macros just run the C++ preprocessor over the Java code before you compile. Of course this assumes you use the C++ macro syntax.
If you don't recall what this does, the preprocessor just replaces #define'd items...
That said I agree with the above - use a decent framework (although IMHO it is a little silly not to have macros in Java).
精彩评论