好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

lombok注解介绍小结

lombok 注解 介绍

lombok注解文档 

lombok官网下载

lombok是一个可以帮助我们简化java代码编写的工具类,尤其是简化javabean的编写,即通过采用注解的方式,消除代码中的构造方法,getter/setter等代码,使我们写的类更加简洁,当然,这带来的副作用就是不易阅读…不过,还是能看得懂吧,废话不多说,先看一下lombok支持的一些常见的注解。

@nonnull @cleanup @getter/@setter @tostring @equalsandhashcode @noargsconstructor/@requiredargsconstructor /@allargsconstructor @data @value @sneakythrows @synchronized @log

@nonnull

这个注解可以用在成员方法或者构造方法的参数前面,会自动产生一个关于此参数的非空检查,如果参数为空,则抛出一个空指针异常,举个例子来看看:

?

1

2

3

4

//成员方法参数加上@nonnull注解

public string getname( @nonnull person p){

   return p.getname();

}

实际效果相当于:

?

1

2

3

4

5

6

public string getname( @nonnull person p){

   if (p== null ){

     throw new nullpointerexception( "person" );

   }

   return p.getname();

}

用在构造方法的参数上效果类似,就不再举例子了。

@cleanup

这个注解用在变量前面,可以保证此变量代表的资源会被自动关闭,默认是调用资源的close()方法,如果该资源有其它关闭方法,可使用@cleanup([methodname])来指定要调用的方法,就用输入输出流来举个例子吧:

?

1

2

3

4

5

6

7

8

9

10

public static void main(string[] args) throws ioexception {

    @cleanup inputstream in = new fileinputstream(args[ 0 ]);

    @cleanup outputstream out = new fileoutputstream(args[ 1 ]);

    byte [] b = new byte [ 1024 ];

    while ( true ) {

     int r = in.read(b);

     if (r == - 1 ) break ;

     out.write(b, 0 , r);

    }

  }

实际效果相当于:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public static void main(string[] args) throws ioexception {

    inputstream in = new fileinputstream(args[ 0 ]);

    try {

     outputstream out = new fileoutputstream(args[ 1 ]);

     try {

      byte [] b = new byte [ 10000 ];

      while ( true ) {

       int r = in.read(b);

       if (r == - 1 ) break ;

       out.write(b, 0 , r);

      }

     } finally {

      if (out != null ) {

       out.close();

      }

     }

    } finally {

     if (in != null ) {

      in.close();

     }

   }

}

是不是简化了很多。

@getter/@setter

这一对注解从名字上就很好理解,用在成员变量前面,相当于为成员变量生成对应的get和set方法,同时还可以为生成的方法指定访问修饰符,当然,默认为public,直接来看下面的简单的例子:

?

1

2

3

4

5

6

7

8

9

10

11

public class programmer{

   @getter

   @setter

   private string name;

 

   @setter (accesslevel. protected )

   private int age;

 

   @getter (accesslevel. public )

   private string language;

}

实际效果相当于:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public class programmer{

   private string name;

   private int age;

   private string language;

 

   public void setname(string name){

     this .name = name;

   }

 

   public string getname(){

     return name;

   }

 

   protected void setage( int age){

     this .age = age;

   }

 

   public string getlanguage(){

     return language;

   }

}

这两个注解还可以直接用在类上,可以为此类里的所有非静态成员变量生成对应的get和set方法。

@tostring/@equalsandhashcode

这两个注解也比较好理解,就是生成tostring,equals和hashcode方法,同时后者还会生成一个canequal方法,用于判断某个对象是否是当前类的实例,生成方法时只会使用类中的非静态和非transient成员变量,这些都比较好理解,就不举例子了。
当然,这两个注解也可以添加限制条件,例如用@tostring(exclude={[param1],[param2]})来排除param1和param2两个成员变量,或者用@tostring(of={[param1],[param2]})来指定使用param1和param2两个成员变量,@equalsandhashcode注解也有同样的用法。

@noargsconstructor/@requiredargsconstructor /@allargsconstructor

这三个注解都是用在类上的,第一个和第三个都很好理解,就是为该类产生无参的构造方法和包含所有参数的构造方法,第二个注解则使用类中所有带有@nonnull注解的或者带有final修饰的成员变量生成对应的构造方法,当然,和前面几个注解一样,成员变量都是非静态的,另外,如果类中含有final修饰的成员变量,是无法使用@noargsconstructor注解的。
三个注解都可以指定生成的构造方法的访问权限,同时,第二个注解还可以用@requiredargsconstructor(staticname=]methodname])的形式生成一个指定名称的静态方法,返回一个调用相应的构造方法产生的对象,下面来看一个生动鲜活的例子:

?

1

2

3

4

5

6

7

8

9

10

@requiredargsconstructor (staticname = "sunsfan" )

@allargsconstructor (access = accesslevel. protected )

@noargsconstructor

public class shape {

   private int x;

   @nonnull

   private double y;

   @nonnull

   private string name;

}

实际效果相当于:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public class shape {

   private int x;

   private double y;

   private string name;

 

   public shape(){

   }

 

   protected shape( int x, double y,string name){

     this .x = x;

     this .y = y;

     this .name = name;

   }

 

   public shape( double y,string name){

     this .y = y;

     this .name = name;

   }

 

   public static shape sunsfan( double y,string name){

     return new shape(y,name);

   }

}

@data/@value

呃!!

@data注解综合了3,4,5和6里面的@requiredargsconstructor注解,其中@requiredargsconstructor使用了类中的带有@nonnull注解的或者final修饰的成员变量,它可以使用@data(staticconstructor=]methodname])来生成一个静态方法,返回一个调用相应的构造方法产生的对象。这个例子就也省略了吧…

@value注解和@data类似,区别在于它会把所有成员变量默认定义为private final修饰,并且不会生成set方法。

@sneakythrows

这个注解用在方法上,可以将方法中的代码用try-catch语句包裹起来,捕获异常并在catch中用lombok.sneakythrow(e)把异常抛出,可以使用@sneakythrows(exception.class)的形式指定抛出哪种异常,很简单的注解,直接看个例子:

?

1

2

3

4

5

6

7

8

9

10

11

public class sneakythrows implements runnable {

   @sneakythrows (unsupportedencodingexception. class )

   public string utf8tostring( byte [] bytes) {

     return new string(bytes, "utf-8" );

   }

 

   @sneakythrows

   public void run() {

     throw new throwable();

   }

}

实际效果相当于:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public class sneakythrows implements runnable {

   @sneakythrows (unsupportedencodingexception. class )

   public string utf8tostring( byte [] bytes) {

     try {

       return new string(bytes, "utf-8" );

     } catch (unsupportedencodingexception uee){

       throw lombok.sneakythrow(uee);

     }

   }

 

   @sneakythrows

   public void run() {

     try {

       throw new throwable();

     } catch (throwable t){

       throw lombok.sneakythrow(t);

     }

   }

}

@synchronized

这个注解用在类方法或者实例方法上,效果和synchronized关键字相同,区别在于锁对象不同,对于类方法和实例方法,synchronized关键字的锁对象分别是类的class对象和this对象,而@synchronized得锁对象分别是私有静态final对象lock和私有final对象lock和私有final对象lock,当然,也可以自己指定锁对象,例子也很简单,往下看:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class synchronized {

   private final object readlock = new object();

 

   @synchronized

   public static void hello() {

     system.out.println( "world" );

   }

 

   @synchronized

   public int answertolife() {

     return 42 ;

   }

 

   @synchronized ( "readlock" )

   public void foo() {

     system.out.println( "bar" );

   }

}

实际效果相当于:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public class synchronized {

   private static final object $lock = new object[ 0 ];

   private final object $lock = new object[ 0 ];

   private final object readlock = new object();

 

   public static void hello() {

    synchronized ($lock) {

     system.out.println( "world" );

    }

   }

 

   public int answertolife() {

    synchronized ($lock) {

     return 42 ;

    }

   }

 

   public void foo() {

    synchronized (readlock) {

     system.out.println( "bar" );

    }

   }

  }

@log

这个注解用在类上,可以省去从日志工厂生成日志对象这一步,直接进行日志记录,具体注解根据日志工具的不同而不同,同时,可以在注解中使用topic来指定生成log对象时的类名。不同的日志注解总结如下(上面是注解,下面是实际作用):

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@commonslog

private static final org.apache.commons.logging.log log = org.apache.commons.logging.logfactory.getlog(logexample. class );

@jbosslog

private static final org.jboss.logging.logger log = org.jboss.logging.logger.getlogger(logexample. class );

@log

private static final java.util.logging.logger log = java.util.logging.logger.getlogger(logexample. class .getname());

@log4j

private static final org.apache.log4j.logger log = org.apache.log4j.logger.getlogger(logexample. class );

@log4j2

private static final org.apache.logging.log4j.logger log = org.apache.logging.log4j.logmanager.getlogger(logexample. class );

@slf4j

private static final org.slf4j.logger log = org.slf4j.loggerfactory.getlogger(logexample. class );

@xslf4j

private static final org.slf4j.ext.xlogger log = org.slf4j.ext.xloggerfactory.getxlogger(logexample. class );

关于lombok的注解先写到这里,当然,还有其他一些注解需要大家自己去摸索,同时lombok一直在扩展,将来肯定会加入更多的注解元素,拭目以待了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/sunsfan/article/details/53542374

查看更多关于lombok注解介绍小结的详细内容...

  阅读:9次