Lombok开发指南

来源:互联网 发布:矩阵的秩怎么求 编辑:程序博客网 时间:2024/06/05 19:27
<body class="theme theme-white">
<div style="visibility: hidden; overflow: hidden; position: absolute; top: 0px; height: 1px; width: auto; padding: 0px; border: 0px; margin: 0px; text-align: left; text-indent: 0px; text-transform: none; line-height: normal; letter-spacing: normal; word-spacing: normal;"><div id="MathJax_SVG_Hidden"></div><svg><defs id="MathJax_SVG_glyphs"><path id="MJMATHI-6C" stroke-width="1" d="M117 59Q117 26 142 26Q179 26 205 131Q211 151 215 152Q217 153 225 153H229Q238 153 241 153T246 151T248 144Q247 138 245 128T234 90T214 43T183 6T137 -11Q101 -11 70 11T38 85Q38 97 39 102L104 360Q167 615 167 623Q167 626 166 628T162 632T157 634T149 635T141 636T132 637T122 637Q112 637 109 637T101 638T95 641T94 647Q94 649 96 661Q101 680 107 682T179 688Q194 689 213 690T243 693T254 694Q266 694 266 686Q266 675 193 386T118 83Q118 81 118 75T117 65V59Z"></path><path id="MJMATHI-6F" stroke-width="1" d="M201 -11Q126 -11 80 38T34 156Q34 221 64 279T146 380Q222 441 301 441Q333 441 341 440Q354 437 367 433T402 417T438 387T464 338T476 268Q476 161 390 75T201 -11ZM121 120Q121 70 147 48T206 26Q250 26 289 58T351 142Q360 163 374 216T388 308Q388 352 370 375Q346 405 306 405Q243 405 195 347Q158 303 140 230T121 120Z"></path><path id="MJMATHI-63" stroke-width="1" d="M34 159Q34 268 120 355T306 442Q362 442 394 418T427 355Q427 326 408 306T360 285Q341 285 330 295T319 325T330 359T352 380T366 386H367Q367 388 361 392T340 400T306 404Q276 404 249 390Q228 381 206 359Q162 315 142 235T121 119Q121 73 147 50Q169 26 205 26H209Q321 26 394 111Q403 121 406 121Q410 121 419 112T429 98T420 83T391 55T346 25T282 0T202 -11Q127 -11 81 37T34 159Z"></path><path id="MJMATHI-6B" stroke-width="1" d="M121 647Q121 657 125 670T137 683Q138 683 209 688T282 694Q294 694 294 686Q294 679 244 477Q194 279 194 272Q213 282 223 291Q247 309 292 354T362 415Q402 442 438 442Q468 442 485 423T503 369Q503 344 496 327T477 302T456 291T438 288Q418 288 406 299T394 328Q394 353 410 369T442 390L458 393Q446 405 434 405H430Q398 402 367 380T294 316T228 255Q230 254 243 252T267 246T293 238T320 224T342 206T359 180T365 147Q365 130 360 106T354 66Q354 26 381 26Q429 26 459 145Q461 153 479 153H483Q499 153 499 144Q499 139 496 130Q455 -11 378 -11Q333 -11 305 15T277 90Q277 108 280 121T283 145Q283 167 269 183T234 206T200 217T182 220H180Q168 178 159 139T145 81T136 44T129 20T122 7T111 -2Q98 -11 83 -11Q66 -11 57 -1T48 16Q48 26 85 176T158 471L195 616Q196 629 188 632T149 637H144Q134 637 131 637T124 640T121 647Z"></path></defs></svg></div><div id="wmd-preview" class="wmd-preview wmd-preview-full-reader"><div class="md-section-divider"></div><div class="md-section-divider"></div><h1 data-anchor-id="uyed" id="lombok开发指南">Lombok开发指南</h1><p data-anchor-id="j5sd"><code>lombok</code> <code>注解</code></p><hr><p data-anchor-id="pxlq">好东西要分享,转载来源:<a href="http://codepub.cn/2015/07/30/Lombok-development-guidelines/" target="_blank">http://codepub.cn/2015/07/30/Lombok-development-guidelines/</a></p><div class="md-section-divider"></div><h2 data-anchor-id="7kn3" id="lombok简介">Lombok简介</h2><p data-anchor-id="t82o">Lombok是一款好用顺手的工具,就像Google Guava一样,在此予以强烈推荐,每一个Java工程师都应该使用它。Lombok是一种Java™实用工具,可用来帮助开发人员消除Java的冗长代码,尤其是对于简单的Java对象(POJO)。它通过注释实现这一目的。通过在开发环境中实现Lombok,开发人员可以节省构建诸如hashCode()和equals()这样的方法以及以往用来分类各种accessor和mutator的大量时间。</p><p data-anchor-id="ygs8">Lombok官网地址:<a href="https://projectlombok.org/" target="_blank">https://projectlombok.org/</a> 里面还提供了一个简短的学习视频。</p><div class="md-section-divider"></div><h2 data-anchor-id="uwus" id="安装lombok">安装Lombok</h2><div class="md-section-divider"></div><h3 data-anchor-id="oyut" id="eclipse安装lombok">Eclipse安装Lombok</h3><p data-anchor-id="cqru">双击Jar安装</p><p data-anchor-id="sls6">首先下载Jar包,下载地址:<a href="http://projectlombok.org/download.html" target="_blank">http://projectlombok.org/download.html</a> <br>
<img src="http://7xig3q.com1.z0.glb.clouddn.com/IntelliJ-plugin-lombok.png" alt="Eclipse安装Lombok" title=""></p><p data-anchor-id="4nr1">注意如果eclipse没有安装到默认目录,那么需要点击Specify选择eclipse.exe所在的路径,然后Install即可完成安装。</p><p data-anchor-id="3f3t">在新建项目之后,使用Lombok如果程序还报错,那么点击eclipse菜单的Project选项的clean,清理一下即可。</p><p data-anchor-id="2vl1">Eclipse手动安装Lombok步骤</p><p data-anchor-id="293n">将lombok.jar复制到myeclipse.ini/eclipse.ini所在的文件夹目录下 <br>
打开eclipse.ini/myeclipse.ini,在最后面插入以下两行并保存: <br>
-Xbootclasspath/a:lombok.jar <br>
-javaagent:lombok.jar <br>
重启eclipse/myeclipse <br>
最后需要注意的是,在使用lombok注解的时候记得要导入lombok.jar包到工程,如果使用的是Maven Project,要在pom.xml中添加依赖,并设置Maven为自动导入,参见IntelliJ部分。</p><pre data-anchor-id="46sc"><code>&lt;dependency&gt;
    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
    &lt;artifactId&gt;lombok&lt;/artifactId&gt;
    &lt;version&gt;1.16.8&lt;/version&gt;
&lt;/dependency&gt;
</code></pre><div class="md-section-divider"></div><h3 data-anchor-id="s3fz" id="intellij安装lombok">IntelliJ安装Lombok</h3><div class="md-section-divider"></div><h4 data-anchor-id="pe85" id="通过intellij的插件中心安装">通过IntelliJ的插件中心安装</h4><p data-anchor-id="p4t0"><img src="http://7xig3q.com1.z0.glb.clouddn.com/IntelliJ-plugin-lombok.png" alt="通过IntelliJ的插件中心安装" title=""> <br>
<img src="http://7xig3q.com1.z0.glb.clouddn.com/IntelliJ-lombok.png" alt="通过IntelliJ的插件中心安装" title=""> <br>
注意一点,在IntelliJ中如果创建的是Maven项目,那么在pom.xml文件中添加依赖后,需要设置Maven为自动导入。 <br>
<img src="http://7xig3q.com1.z0.glb.clouddn.com/IntelliJ-maven-auto-import.png" alt="设置Maven为自动导入" title=""></p><div class="md-section-divider"></div><h4 data-anchor-id="lmd2" id="intellij手动安装lombok">IntelliJ手动安装Lombok</h4><p data-anchor-id="gqsx">如果不想通过IntelliJ的插件中心安装的话,也可以手动安装,详细步骤参见Github上的说明:<a href="https://github.com/mplushnikov/lombok-intellij-plugin" target="_blank">https://github.com/mplushnikov/lombok-intellij-plugin</a></p><p data-anchor-id="6amo">简单点说手动安装步骤如下: <br>
Download the latest release and install it manually using Preferences &gt; Plugins &gt; Install plugin from disk…</p><div class="md-section-divider"></div><h2 data-anchor-id="yn4f" id="lombok用法">Lombok用法</h2><p data-anchor-id="tld8">Lombok注解说明</p><p data-anchor-id="lk9m">val:用在局部变量前面,相当于将变量声明为final; <br>
@NonNull:给方法参数增加这个注解会自动在方法内对该参数进行是否为空的校验,如果为空,则抛出NPE(NullPointerException); <br>
@Cleanup:自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成try-finally这样的代码来关闭流; <br>
@Getter/@Setter:用在属性上,再也不用自己手写setter和getter方法了,还可以指定访问范围; <br>
@ToString:用在类上,可以自动覆写toString方法,当然还可以加其他参数,例如@ToString(exclude=”id”)排除id属性,或者@ToString(callSuper=true, includeFieldNames=true)调用父类的toString方法,包含所有属性 <br>
@EqualsAndHashCode:用在类上,自动生成equals方法和hashCode方法; <br>
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor:用在类上,自动生成无参构造和使用所有参数的构造函数以及把所有@NonNull属性作为参数的构造函数,如果指定staticName = “of”参数,同时还会生成一个返回类对象的静态工厂方法,比使用构造函数方便很多; <br>
@Data:注解在类上,相当于同时使用了@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstrutor这些注解,对于POJO类十分有用; <br>
@Value:用在类上,是@Data的不可变形式,相当于为属性添加final声明,只提供getter方法,而不提供setter方法; <br>
@Builder:用在类、构造器、方法上,为你提供复杂的builder APIs,让你可以像如下方式一样调用Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();更多说明参考Builder; <br>
@SneakyThrows:自动抛受检异常,而无需显式在方法上使用throws语句; <br>
@Synchronized:用在方法上,将方法声明为同步的,并自动加锁,而锁对象是一个私有的属性<span class="MathJax_Preview"></span><span class="MathJax_SVG" id="MathJax-Element-1-Frame" role="textbox" aria-readonly="true" style="font-size: 100%; display: inline-block;"><svg xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 -784.7362297499269 2456.59 1143.4033969998538" style="width: 5.729ex; height: 2.604ex; vertical-align: -0.938ex; margin: 1px 0px;"><g stroke="black" fill="black" stroke-width="0" transform="matrix(1 0 0 -1 0 0)"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-6C"></use><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-6F" x="298" y="0"></use><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-63" x="784" y="0"></use><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-6B" x="1217" y="0"></use><g transform="translate(1739,0)"><text font-family="STIXGeneral,'Arial Unicode MS',serif" font-style="" font-weight="" stroke="none" transform="scale(44.849375) matrix(1 0 0 -1 0 0)">或</text></g></g></svg></span><script type="math/tex" id="MathJax-Element-1">lock或</script>LOCK,而java中的synchronized关键字锁对象是this,锁在this或者自己的类对象上存在副作用,就是你不能阻止非受控代码去锁this或者类对象,这可能会导致竞争条件或者其它线程错误; <br>
@Getter(lazy=true):可以替代经典的Double Check Lock样板代码 <br>
@Log:根据不同的注解生成不同类型的log对象,但是实例名称都是log,有六种可选实现类 <br>
@CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class); <br>
@Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName()); <br>
@Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class); <br>
@Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); <br>
@Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class); <br>
@XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);</p><div class="md-section-divider"></div><h3 data-anchor-id="6sly" id="lombok使用示例">Lombok使用示例</h3><p data-anchor-id="mfwq">val示例</p><pre data-anchor-id="9xl4"><code>public static void main(String[] args) {
    val sets = new HashSet&lt;String&gt;();
    val lists = new ArrayList&lt;String&gt;();
    val maps = new HashMap&lt;String, String&gt;();
    //=&gt;相当于如下
    final Set&lt;String&gt; sets2 = new HashSet&lt;&gt;();
    final List&lt;String&gt; lists2 = new ArrayList&lt;&gt;();
    final Map&lt;String, String&gt; maps2 = new HashMap&lt;&gt;();
}
</code></pre><p data-anchor-id="vd8x">@NonNull示例</p><pre data-anchor-id="zt5r"><code>public void notNullExample(@NonNull String string) {
    string.length();
}
//=&gt;相当于
public void notNullExample(String string) {
    if (string != null) {
        string.length();
    } else {
        throw new NullPointerException("null");
    }
}
</code></pre><p data-anchor-id="t7nk">@Cleanup示例</p><pre data-anchor-id="jb0g"><code>public static void main(String[] args) {
    try {
        @Cleanup InputStream inputStream = new FileInputStream(args[0]);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    //=&gt;相当于
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(args[0]);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
</code></pre><p data-anchor-id="eci8">@Getter/@Setter示例</p><pre data-anchor-id="u79z"><code>@Setter(AccessLevel.PUBLIC)
@Getter(AccessLevel.PROTECTED)
private int id;
private String shap;
</code></pre><p data-anchor-id="revl">@ToString示例</p><pre data-anchor-id="4fam"><code>@ToString(exclude = "id", callSuper = true, includeFieldNames = true)
public class LombokDemo {
    private int id;
    private String name;
    private int age;


    public static void main(String[] args) {
        //输出LombokDemo(super=LombokDemo@48524010, name=null, age=0)
        System.out.println(new LombokDemo());
    }
}
</code></pre><p data-anchor-id="4hst">@EqualsAndHashCode示例</p><pre data-anchor-id="lixr"><code>@EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
public class LombokDemo {
    private int id;
    private String shap;
}
</code></pre><p data-anchor-id="ewez">@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor示例</p><pre data-anchor-id="l92g"><code>@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor
public class LombokDemo {
    @NonNull
    private int id;
    @NonNull
    private String shap;
    private int age;
    public static void main(String[] args) {
        new LombokDemo(1, "circle");
        //使用静态工厂方法
        LombokDemo.of(2, "circle");
        //无参构造
        new LombokDemo();
        //包含所有参数
        new LombokDemo(1, "circle", 2);
    }
}
</code></pre><p data-anchor-id="83x7">@Data示例</p><pre data-anchor-id="ng4j"><code>import lombok.Data;
@Data
public class Menu {
    private String shopId;
    private String skuMenuId;
    private String skuName;
    private String normalizeSkuName;
    private String dishMenuId;
    private String dishName;
    private String dishNum;
    //默认阈值
    private float thresHold = 0;
    //新阈值
    private float newThresHold = 0;
    //总得分
    private float totalScore = 0;
}
</code></pre><p data-anchor-id="jypf">在IntelliJ中按下Ctrl+F12就可以看到Lombok已经为我们自动生成了一系列的方法。 <br>
<img src="http://7xig3q.com1.z0.glb.clouddn.com/IntelliJ-lombok-java-demo.jpg" alt="Lombok自动生成的方法" title=""></p><p data-anchor-id="0lr2">@Value示例</p><pre data-anchor-id="y2nk"><code>@Value
public class LombokDemo {
    @NonNull
    private int id;
    @NonNull
    private String shap;
    private int age;
    //相当于
    private final int id;
    public int getId() {
        return this.id;
    }
    ...
}
</code></pre><p data-anchor-id="wptw">@Builder示例</p><pre data-anchor-id="u4nf"><code>@Builder
public class BuilderExample {
    private String name;
    private int age;
    @Singular
    private Set&lt;String&gt; occupations;
    public static void main(String[] args) {
        BuilderExample test = BuilderExample.builder().age(11).name("test").build();
    }
}
</code></pre><p data-anchor-id="uqv5">@SneakyThrows示例</p><pre data-anchor-id="2cqz"><code>import lombok.SneakyThrows;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class Test {
    @SneakyThrows()
    public void read() {
        InputStream inputStream = new FileInputStream("");
    }
    @SneakyThrows
    public void write() {
        throw new UnsupportedEncodingException();
    }
    //相当于
    public void read() throws FileNotFoundException {
        InputStream inputStream = new FileInputStream("");
    }
    public void write() throws UnsupportedEncodingException {
        throw new UnsupportedEncodingException();
    }
}
</code></pre><p data-anchor-id="7jcb">@Synchronized示例</p><pre data-anchor-id="iifl"><code>public class SynchronizedDemo {
    @Synchronized
    public static void hello() {
        System.out.println("world");
    }
    //相当于
    private static final Object $LOCK = new Object[0];
        public static void hello() {
            synchronized ($LOCK) {
            System.out.println("world");
        }
    }
}
</code></pre><p data-anchor-id="thaz">@Getter(lazy = true)</p><pre data-anchor-id="n22u"><code>public class GetterLazyExample {
    @Getter(lazy = true)
    private final double[] cached = expensive();
    private double[] expensive() {
        double[] result = new double[1000000];
        for (int i = 0; i &lt; result.length; i++) {
            result[i] = Math.asin(i);
        }
        return result;
    }
}
</code></pre><p data-anchor-id="vwq7">相当于如下所示</p><pre data-anchor-id="bx7j"><code>import java.util.concurrent.atomic.AtomicReference;
public class GetterLazyExample {
    private final AtomicReference&lt;java.lang.Object&gt; cached = new AtomicReference&lt;&gt;();
    public double[] getCached() {
        java.lang.Object value = this.cached.get();
        if (value == null) {
            synchronized (this.cached) {
                value = this.cached.get();
                if (value == null) {
                    final double[] actualValue = expensive();
                    value = actualValue == null ? this.cached : actualValue;
                    this.cached.set(value);
                }
            }
        }
        return (double[]) (value == this.cached ? null : value);
    }
    private double[] expensive() {
        double[] result = new double[1000000];
        for (int i = 0; i &lt; result.length; i++) {
            result[i] = Math.asin(i);
        }
        return result;
    }
}
</code></pre></div>
</body>
原创粉丝点击