• lombok使用


    TOC

    lombok使用

    类注解:

    data

    @Data :注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法,

    public class Demo3 {
        private Long id;
        private String name;
    
        public Demo3() {
        }
    
        public Long getId() {
            return this.id;
        }
    
        public String getName() {
            return this.name;
        }
    
        public void setId(final Long id) {
            this.id = id;
        }
    
        public void setName(final String name) {
            this.name = name;
        }
    
        public boolean equals(final Object o) {
            if (o == this) {
                return true;
            } else if (!(o instanceof Demo3)) {
                return false;
            } else {
                Demo3 other = (Demo3)o;
                if (!other.canEqual(this)) {
                    return false;
                } else {
                    Object this$id = this.getId();
                    Object other$id = other.getId();
                    if (this$id == null) {
                        if (other$id != null) {
                            return false;
                        }
                    } else if (!this$id.equals(other$id)) {
                        return false;
                    }
    
                    Object this$name = this.getName();
                    Object other$name = other.getName();
                    if (this$name == null) {
                        if (other$name != null) {
                            return false;
                        }
                    } else if (!this$name.equals(other$name)) {
                        return false;
                    }
    
                    return true;
                }
            }
        }
    
        protected boolean canEqual(final Object other) {
            return other instanceof Demo3;
        }
    
        public int hashCode() {
            int PRIME = true;
            int result = 1;
            Object $id = this.getId();
            int result = result * 59 + ($id == null ? 43 : $id.hashCode());
            Object $name = this.getName();
            result = result * 59 + ($name == null ? 43 : $name.hashCode());
            return result;
        }
    
        public String toString() {
            return "Demo3(id=" + this.getId() + ", name=" + this.getName() + ")";
        }
    }
    

    @Data(staticConstructor="methodName")来生成一个静态方法,返回一个调用相应的构造方法产生的对象。

    //默认
    public Demo3() {}
    
    //@Data(staticConstructor="getDemo3")
        private Demo3() {
        }
    
        public static Demo3 getDemo3() {
            return new Demo3();
        }

    Setter和Getter

    • @Setter:注解在属性上;为属性提供 setting 方法
    • @Getter:注解在属性上;为属性提供 getting 方法

    Setter和Getter也可以设置到字段上,并设置方法级别

    public class Programmer{
          @Getter
          @Setter
          private String name;
    
          @Setter(AccessLevel.PROTECTED)
          private int age;
    
          @Getter(AccessLevel.PUBLIC)
          private String language;
      }
      ----------------
      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;}
      }

    Value

    @Value :Getter、toString()、equals()、hashCode()、一个全参的构造方法

    Builder

    @Builder:Builder内部类和全字段的构造器,没有Getter、Setter、toString()。

    @ToString
    @Builder
    public class Demo3 {
        private Long id;
        private String name;
    
        public static void main(String[] args) {
            Demo3 nihao = Demo3.builder().id(12L).name("nihao").build();
            System.out.println(nihao);
        }
    }
    //Demo3(id=12, name=nihao)

    ToString

    @ToString:toString()方法:@ToString(exclude={"param1","param2"})来排除param1和param2两个成员变量,或者用@ToString(of={"param1","param2"})来指定使用param1和param2两个成员变量

    EqualsAndHashCode

    @EqualsAndHashCode:equals、canEqual(用于判断某个对象是否是当前类的实例,生成方法时只会使用类中的非静态非transient成员变量)和hashcode方法,@EqualsAndHashCode(exclude={“param1”,“param2”})来排除param1和param2两个成员变量,或者用@EqualsAndHashCode(of={“param1”,“param2”})来指定使用param1和param2两个成员变量

    继承类一般都会加上:@EqualsAndHashCode(callSuper=false)

    Cleanup

    @Cleanup:该注解的对象,如Stream对象,如果有close()方法,那么在该对象作用域离开时会自动关闭。

        @SneakyThrows  //等同于try/catch 捕获异常
        public static void main(String[] args)  {
            @Cleanup// : 可以关闭流
            BufferedReader br = new BufferedReader(new FileReader("aa.txt"));
            @Cleanup// : 可以关闭流
            BufferedWriter bw = new BufferedWriter(new FileWriter("bb.txt"));
    
            int ch;
            while ((ch = br.read()) != -1) {
                bw.write(ch);
            }
    //        bw.close();
    //        br.close();
        }
    -----编译之后
        public static void main(String[] args) {
            try {
                BufferedReader br = new BufferedReader(new FileReader("aa.txt"));
    
                try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter("bb.txt"));
    
                    int ch;
                    try {
                        while((ch = br.read()) != -1) {
                            bw.write(ch);
                        }
                    } finally {
                        if (Collections.singletonList(bw).get(0) != null) {
                            bw.close();
                        }
    
                    }
                } finally {
                    if (Collections.singletonList(br).get(0) != null) {
                        br.close();
                    }
    
                }
    
            } catch (Throwable var14) {
                throw var14;
            }
        }

    日志

    • @Log:一组日志相关注解,标注的类会隐式的定一个了一个名为log的日志对象。
    • @Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象
    • @Log4j2@Slf4j@XSlf4j,@CommonsLog,@JBossLog
     @Log
    public  class User {
        public  static  void  main(String[] args) {
            System.out.println(log.getClass()); 
            log.info("app log."); 
        }
    }

    构造器

    构造器(上面的三个注解)可以使用access属性定制访问级别,如:@NoArgsConstructor(access = AccessLevel.PRIVATE)

    • @NoArgsConstructor:注解在类上;为类提供一个无参的构造方法,有时候我们会使用到单例模式,这个时候我们需要将构造器私有化,那么就可以使用这样一个属性access设置构造器的权限.

      当类中有final字段没有被初始化时,编译器会报错,但是也可用@NoArgsConstructor(force = true),那么Lombok就会为没有初始化的final字段设置默认值 0 / false / null, 这样编译器就不会报错,如下所示:

      @NoArgsConstructor(force = true)
      public class User {
        private final String gender;
        private String username;
        private String password;
      }
      // 编译后:
      public class User {
        private final String gender = null;
        private String username;
        private String password;
      
        public User() { }
      }

    对于具有约束的字段(例如使用了@NonNull注解的字段),不会生成字段检查

    • staticName:定义一个姓的构造方法,默认的构造方法会被私有化
      @NoArgsConstructor(staticName = "UserHa")//@Data(staticConstructor="methodName")
      public class User {
          private String username;
          private String password;
      }
      // 编译后:
      public class User {
          private String username;
          private String password;
      
          private User() { } //私有了
      
          public static User UserHa() { //根据注解,生成了一个新的注解
              return new User();
          }
      }
      • @AllArgsConstructor:注解在类上;为类提供一个全参的构造方法,(不包括已初始化的final字段)
      • @RequiredArgsConstructor: 增加必选参数构造器,只能是类中所有带有 @NonNull注解的和以final修饰的未经初始化的字段才会被纳入 RequiredArgsConstructor 构造器中。
      @RequiredArgsConstructor
      public class User {
        private final String gender;
        @NonNull
        private String username;
        private String password;
      }
      
      // 编译后:
      public class User {
        private final String gender;
        @NonNull
        private String username;
        private String password;
      
        public User(String gender, @NonNull String username) {
            //@NonNull的校验不能为null
            if (username == null) {
                throw new NullPointerException("username is marked @NonNull but is null");
            } else {
                this.gender = gender;
                this.username = username;
            }
        }
      }
      • Constructor 全局配置
      # 如果设置为true,则lombok将向生成的构造函数添加 @java.beans.ConstructorProperties。
      
      lombok.anyConstructor.addConstructorProperties = [true | false] (default: false)
      
      # 是否禁用这几种构造器注解
      
      lombok.[allArgsConstructor|requiredArgsConstructor|noArgsConstructor].flagUsage = [warning | error] (default: not set)
      lombok.anyConstructor.flagUsage = [warning | error] (default: not set)
      
      # 是否支持复制现有的注解,在本类中使用。e.g. @Nullable/@NonNull annotations
      
      lombok.copyableAnnotations = [A list of fully qualified types] (default: empty list)
    • 测试 addConstructorProperties

      全局配置文件内容

      config.stopBubbling = true
      
      # 首先清除原有配置
      
      clear lombok.anyConstructor.addConstructorProperties
      
      # 设置新的配置
      
      lombok.anyConstructor.addConstructorProperties = true

      实体类

      //值得注意一点的是:@ConstructorProperties只能用在JDK 6中
      @AllArgsConstructor
      public class User {
          private String username;
          private String password;
      }
      // 编译后:
      public class User {
          private String username;
          private String password;
      
          @ConstructorProperties({"username", "password"})        // 被添加
          public User(String username, String password) {
              this.username = username;
              this.password = password;
          }
      }

    Accessors

    @Accessors:用于配置getter和setter方法的生成结果

    • fluent:

      fluent的中文含义是流畅的,设置为true,则getter和setter方法的方法名都是基础属性名,且setter方法返回当前对象。

      @Data
      @Accessors(fluent = true)
      public class User {
        private Long id;
        private String name;
      
        // 生成的getter和setter方法如下,方法体略
        public Long id() {}
        public User id(Long id) {}
        public String name() {}
        public User name(String name) {}
      }
    • chain:设置为true,则setter方法返回当前对象。
      @Data
      @Accessors(chain = true)
      public class User {
        private Long id;
        private String name;
      
        // 生成的setter方法如下,方法体略
        public User setId(Long id) {}
        public User setName(String name) {}
      }
    • prefix:用于生成getter和setter方法的字段名会忽视指定前缀(遵守驼峰命名)。
      @Data
      @Accessors(prefix = "p")
      class User {
        private Long pId;
        private String pName;
      
        // 生成的getter和setter方法如下,方法体略
        public Long getId() {}
        public void setId(Long id) {}
        public String getName() {}
        public void setName(String name) {}
      }

    Synchronized

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

    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");
        }
    }

    编译后:

    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");
         }
       }
    }

    属性注解

    懒加载

    是对象初始化时,该字段并不会真正的初始化;而是第一次访问该字段时才进行初始化字段的操作。

    • lazy
    @Getter(lazy=true) 懒加载
    package com.pollyduan;
    
    import lombok.Data;
    import lombok.Getter;
    
    @Data
    public class GetterLazyExample {
        @Getter(lazy = true)
        private final int[] cached = expensive();
        private Integer id;
    
        private int[] expensive() {
            int[] result = new int[100];
            for (int i = 0; i < result.length; i++) {
                result[i] = i;
                System.out.println(i);
            }
            System.out.println("cached 初始化完成。");
            return result;
        }
        public static void main(String[] args) {
            GetterLazyExample obj=new GetterLazyExample();
            obj.setId(1001);
            System.out.println("打印id:"+obj.getId());
            System.out.println("cached 还没有初始化哟。");
            // obj.getCached();
        }
    }
    打印id:1001
    cached 还没有初始化。
    打开obj.getCached();的注释,获取这个字段的值,你就会发现它真的初始化了。
    打印id:1001 cached 还没有初始化哟。 0  1  ...  97  98  99 cached 初始化完成。
    • @SneakyThrows 隐藏异常,自动捕获检查异常。可以将方法中的代码用try-catch语句包裹起来,捕获异常并在catch中用Lombok.sneakyThrow(e)把异常抛出,可以使用@SneakyThrows(异常类.class)的形式指定抛出哪种异常

    提示:不过这并不是友好的编码方式,因为你编写的api的使用者,不能显式的获知需要处理检查异常。

    import lombok.SneakyThrows;
    
    public class SneakyThrowsExample {
        @SneakyThrows({UnsupportedEncodingException.class})
        public void test(byte[] bytes) {
            String str = new String(bytes, "UTF8");
        }
        @SneakyThrows({UnsupportedEncodingException.class,FileNotFoundException.class})
        public void test2(byte[] bytes) {
            FileInputStream file=new FileInputStream("no_texists.txt");
            String str=new String(bytes, "UTF8");
        }
        @SneakyThrows
        public void test3(byte[] bytes) {
            FileInputStream file=new FileInputStream("no_texists.txt");
            String str=new String(bytes, "UTF8");
        }
    
    }

    编译之后:

    package com.pollyduan;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.UnsupportedEncodingException;
    
    import lombok.SneakyThrows;
    
    public class SneakyThrowsExample {
        public void test(byte[] bytes) {
            try {
                String str = new String(bytes, "UTF8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        public void test2(byte[] bytes) {
            try {
                FileInputStream file=new FileInputStream("no_texists.txt");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                String str=new String(bytes, "UTF8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        public void test3(byte[] bytes) {
            try {
                FileInputStream file=new FileInputStream("no_texists.txt");
                String str=new String(bytes, "UTF8");
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    
    }

    辅助注解

    NonNull

    @NonNull:

    标记在字段上,表示非空字段。

    标注在方法参数上,会在第一次使用该参数是判断是否为空,如果参数为空,则抛出一个空指针异常 。

    //成员方法参数加上@NonNull注解
    public String getName(@NonNull Person p){
        return p.getName();
    }
    ---------------
    public String getName(@NonNull Person p){
        if(p==null){
            throw new NullPointerException("person");
        }
        return p.getName();
    }

    Cleanup

    @Cleanup:自动关闭资源,如果该资源有其它关闭方法,可使用@Cleanup(“methodName”)来指定要调用的方法.

    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);
         }
    }
    --------------------
    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();
           }
        }
    }




  • 相关阅读:
    【PAT甲级】1063 Set Similarity (25 分)
    【PAT甲级】1062 Talent and Virtue (25 分)
    【PAT甲级】1061 Dating (20 分)
    Codeforces Global Round 5E(构造,思维)
    Codeforces Round #592 (Div. 2)G(模拟)
    POJ 刷题进程.1
    登录页面 (带遮罩层的) ---2017-04--5
    回答: 2017-03-19的关于css+div布局的疑问 2017-04-05
    关于js高度和宽度的获取 ----2017-03-29
    如何用写js弹出层 ----2017-03-29
  • 原文地址:https://www.cnblogs.com/ziyue7575/p/9c9e4d16f87c0b328c6179391e528cf5.html
Copyright © 2020-2023  润新知