Java Magazine, May/June 2017
ORACLE COM JAVAMAGAZINE MAY JUNE 2017 14 libraries ing to your choice of logging API on any class that requires logging capability For instance if you wish to use a logging API say Log4j 2 each class that uses the logger must declare something similar to the following public class ClassName private static final org apache log4j Logger log org apache log4j Logger getLogger ClassName class Use log variable as needed Lombok makes it possible to do the following instead @ Log4j2 public class ClassName Use log variable as needed Listing 6 in the downloadable code shows an example using Log4j 2 The name of the logger will automatically be the same as its containing class name However this can be customized by specifying the topic attribute of the respective logging annotation For a complete listing of supported logging APIs refer to the Lombok documentation and the Lombok Javadoc Other Useful Items There are several other useful features Lombok offers that I havent yet covered Lets go through a couple of the most highly used Informal declaration The val keyword can be used in place of an object type when you declare a local final variable much like the val keyword that you have seen in alternative languages such as Groovy or Jython Take the following code for instance final ArrayList Job myJobs new ArrayList Job Using the val keyword you can change the code to the following val myJobs new ArrayList Job There are some considerations for using the val keyword First as mentioned previously it marks the method declaration as final Therefore if you later need to change the value of the variable using the val keyword is not possible It also does not work correctly in some IDEs so if you are trying to mark local variables as final in those IDEs they are flagged as errors Be sneaky with exceptions There are occasions where exception handling can become a burden and Id argue that this is typically the case when you are working with boilerplate exceptions Most of the time Java allows you to easily see where problems exist via the use of checked exceptions However in those cases where checked exceptions are burdensome you can easily hide them using Lombok The @ SneakyThrows annotation can be placed on a method to essentially swallow the exceptions allowing you to omit the try catch block completely The annotation allows a method to handle all exceptions quietly or you can specify exactly which exceptions to ignore by passing the exception classes to the annotation as attributes Listing 7 in the downloadable code demonstrates the use of @ SneakyThrows specifying which exceptions to swallow The delombok utility can be applied to your code to convert code that uses Lombok back to vanilla Java
You must have JavaScript enabled to view digital editions.