摘要:每個用的孩子都應該了解下主要依賴編譯時代碼生成技術,幫你自動生成基于模板的常用的代碼,譬如最常見的與。另一種是通過類似于這樣基于注解的在運行時利用反射動態添加,不過這樣的缺陷是會影響性能,并且有一定局限性。
Lombok
每個用Java的孩子都應該了解下Lombok
Lombok主要依賴編譯時代碼生成技術,幫你自動生成基于模板的常用的Java代碼,譬如最常見的Getter與Setter。之前動態的插入Getter與Setter主要有兩種,一個是像Intellij與Eclipse這樣在開發時動態插入,缺點是這樣雖然不用你手動寫,但是還是會讓你的代碼異常的冗長。另一種是通過類似于Spring這樣基于注解的在運行時利用反射動態添加,不過這樣的缺陷是會影響性能,并且有一定局限性。
Quick Start Installation文章的Github Repo
部分測試代碼參考這里
筆者目前用的開發環境是Intellij+Gradle,這里只介紹下這種搭建方式,其他的基于Eclipse或者Maven的可以到官網主頁查看。
(1)在Intellij中添加Plugin
Go to File > Settings > Plugins
Click on Browse repositories...
Search for Lombok Plugin
Click on Install plugin
Restart Android Studio
(2)允許注解處理
Settings -> Compiler -> Annotation Processors
(3)Gradle中添加依賴
compile "org.projectlombok:lombok:1.12.6"動態類型推導 Data Model:數據模型 Getter&Setter
源代碼:
import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; public class GetterSetterExample { /** * Age of the person. Water is wet. * * @param age New value for this person"s age. Sky is blue. * @return The current value of this person"s age. Circles are round. */ @Getter @Setter private int age = 10; /** * Name of the person. * -- SETTER -- * Changes the name of this person. * * @param name The new value. */ @Setter(AccessLevel.PROTECTED) private String name; @Override public String toString() { return String.format("%s (age: %d)", name, age); } }
編譯之后的代碼:
public class GetterSetterExample { /** * Age of the person. Water is wet. */ private int age = 10; /** * Name of the person. */ private String name; @Override public String toString() { return String.format("%s (age: %d)", name, age); } /** * Age of the person. Water is wet. * * @return The current value of this person"s age. Circles are round. */ public int getAge() { return age; } /** * Age of the person. Water is wet. * * @param age New value for this person"s age. Sky is blue. */ public void setAge(int age) { this.age = age; } /** * Changes the name of this person. * * @param name The new value. */ protected void setName(String name) { this.name = name; } }Lazy Getter
源代碼:
import lombok.Getter; public class GetterLazyExample { @Getter(lazy=true) private final double[] cached = expensive(); private double[] expensive() { double[] result = new double[1000000]; for (int i = 0; i < result.length; i++) { result[i] = Math.asin(i); } return result; } }
編譯之后:
public class GetterSetterExample { /** * Age of the person. Water is wet. */ private int age = 10; /** * Name of the person. */ private String name; @Override public String toString() { return String.format("%s (age: %d)", name, age); } /** * Age of the person. Water is wet. * * @return The current value of this person"s age. Circles are round. */ public int getAge() { return age; } /** * Age of the person. Water is wet. * * @param age New value for this person"s age. Sky is blue. */ public void setAge(int age) { this.age = age; } /** * Changes the name of this person. * * @param name The new value. */ protected void setName(String name) { this.name = name; } }Data
源代碼:
import lombok.AccessLevel; import lombok.Setter; import lombok.Data; import lombok.ToString; @Data public class DataExample { private final String name; @Setter(AccessLevel.PACKAGE) private int age; private double score; private String[] tags; @ToString(includeFieldNames=true) @Data(staticConstructor="of") public static class Exercise{ private final String name; private final T value; } }
編譯后:
import java.util.Arrays; public class DataExample { private final String name; private int age; private double score; private String[] tags; public DataExample(String name) { this.name = name; } public String getName() { return this.name; } void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public void setScore(double score) { this.score = score; } public double getScore() { return this.score; } public String[] getTags() { return this.tags; } public void setTags(String[] tags) { this.tags = tags; } @Override public String toString() { return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")"; } protected boolean canEqual(Object other) { return other instanceof DataExample; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof DataExample)) return false; DataExample other = (DataExample) o; if (!other.canEqual((Object)this)) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false; if (this.getAge() != other.getAge()) return false; if (Double.compare(this.getScore(), other.getScore()) != 0) return false; if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; final long temp1 = Double.doubleToLongBits(this.getScore()); result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode()); result = (result*PRIME) + this.getAge(); result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32)); result = (result*PRIME) + Arrays.deepHashCode(this.getTags()); return result; } public static class ExerciseObject Constructor{ private final String name; private final T value; private Exercise(String name, T value) { this.name = name; this.value = value; } public static Exercise of(String name, T value) { return new Exercise (name, value); } public String getName() { return this.name; } public T getValue() { return this.value; } @Override public String toString() { return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")"; } protected boolean canEqual(Object other) { return other instanceof Exercise; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Exercise)) return false; Exercise> other = (Exercise>) o; if (!other.canEqual((Object)this)) return false; if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false; if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode()); result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode()); return result; } } }
源代碼
import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.AllArgsConstructor; import lombok.NonNull; @RequiredArgsConstructor(staticName = "of") @AllArgsConstructor(access = AccessLevel.PROTECTED) public class ConstructorExample{ private int x, y; @NonNull private T description; @NoArgsConstructor public static class NoArgsExample { @NonNull private String field; } }
編譯之后:
public class ConstructorExampleBuilder{ private int x, y; @NonNull private T description; private ConstructorExample(T description) { if (description == null) throw new NullPointerException("description"); this.description = description; } public static ConstructorExample of(T description) { return new ConstructorExample (description); } @java.beans.ConstructorProperties({"x", "y", "description"}) protected ConstructorExample(int x, int y, T description) { if (description == null) throw new NullPointerException("description"); this.x = x; this.y = y; this.description = description; } public static class NoArgsExample { @NonNull private String field; public NoArgsExample() { } } }
源代碼:
package wx.toolkits.basic.class_object.utils.lombok.object; import lombok.experimental.Builder; import java.util.Set; @Builder public class BuilderExample { private String name; private int age; private Setoccupations; public static void main(String args[]) { BuilderExample builderExample = BuilderExample.builder().build(); } }
編譯之后的源代碼:
import java.util.Set; public class BuilderExample { private String name; private int age; private SetException:異常處理 NonNulloccupations; BuilderExample(String name, int age, Set occupations) { this.name = name; this.age = age; this.occupations = occupations; } public static BuilderExampleBuilder builder() { return new BuilderExampleBuilder(); } public static class BuilderExampleBuilder { private String name; private int age; private java.util.ArrayList occupations; BuilderExampleBuilder() { } public BuilderExampleBuilder name(String name) { this.name = name; return this; } public BuilderExampleBuilder age(int age) { this.age = age; return this; } public BuilderExampleBuilder occupation(String occupation) { if (this.occupations == null) { this.occupations = new java.util.ArrayList (); } this.occupations.add(occupation); return this; } public BuilderExampleBuilder occupations(Collection extends String> occupations) { if (this.occupations == null) { this.occupations = new java.util.ArrayList (); } this.occupations.addAll(occupations); return this; } public BuilderExampleBuilder clearOccupations() { if (this.occupations != null) { this.occupations.clear(); } return this; } public BuilderExample build() { // complicated switch statement to produce a compact properly sized immutable set omitted. // go to https://projectlombok.org/features/Singular-snippet.html to see it. Set occupations = ...; return new BuilderExample(name, age, occupations); } @java.lang.Override public String toString() { return "BuilderExample.BuilderExampleBuilder(name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")"; } } }
源代碼:
import lombok.NonNull; public class NonNullExample extends Something { private String name; public NonNullExample(@NonNull Person person) { super("Hello"); this.name = person.getName(); } }
編譯之后:
import lombok.NonNull; public class NonNullExample extends Something { private String name; public NonNullExample(@NonNull Person person) { super("Hello"); if (person == null) { throw new NullPointerException("person"); } this.name = person.getName(); } }SneakyThrows
源代碼:
import lombok.SneakyThrows; public class SneakyThrowsExample implements Runnable { @SneakyThrows(UnsupportedEncodingException.class) public String utf8ToString(byte[] bytes) { return new String(bytes, "UTF-8"); } @SneakyThrows public void run() { throw new Throwable(); } }
編譯之后:
import lombok.Lombok; public class SneakyThrowsExample implements Runnable { public String utf8ToString(byte[] bytes) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw Lombok.sneakyThrow(e); } } public void run() { try { throw new Throwable(); } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } }Thread:線程 Synchronized
源代碼:
import lombok.Synchronized; public class SynchronizedExample { 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 SynchronizedExample { 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"); } } }Utils Cleanup
源代碼:
import lombok.Cleanup; import java.io.*; public class CleanupExample { 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[10000]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } }
編譯之后:
import java.io.*; public class CleanupExample { 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(); } } } }Log:日志
使用@Log或者類似注解可以為類自動創建一個log對象,其效果如下所示:
@CommonsLog Creates private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LogExample.class); @Log Creates private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName()); @Log4j Creates private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class); @Log4j2 Creates private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); @Slf4j Creates private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class); @XSlf4j Creates private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
使用了Lombok之后的代碼如下:
import lombok.extern.java.Log; import lombok.extern.slf4j.Slf4j; @Log public class LogExample { public static void main(String... args) { log.error("Something"s wrong here"); } } @Slf4j public class LogExampleOther { public static void main(String... args) { log.error("Something else is wrong here"); } } @CommonsLog(topic="CounterLog") public class LogExampleCategory { public static void main(String... args) { log.error("Calling the "CounterLog" with a message"); } }
編譯之后的代碼如下:
public class LogExample { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName()); public static void main(String... args) { log.error("Something"s wrong here"); } } public class LogExampleOther { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class); public static void main(String... args) { log.error("Something else is wrong here"); } } public class LogExampleCategory { private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog"); public static void main(String... args) { log.error("Calling the "CounterLog" with a message"); } }
其他可配置的參數為:
lombok.log.fieldName = an identifier (default: log)
The generated logger fieldname is by default "log", but you can change it to a different name with this setting.
lombok.log.fieldIsStatic = [true | false] (default: true)
Normally the generated logger is a static field. By setting this key to false, the generated field will be an instance field instead.
lombok.log.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of any of the various log annotations as a warning or error if configured.
lombok.log.apacheCommons.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @lombok.extern.apachecommons.CommonsLog as a warning or error if configured.
lombok.log.javaUtilLogging.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @lombok.extern.java.Log as a warning or error if configured.
lombok.log.log4j.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @lombok.extern.log4j.Log4j as a warning or error if configured.
lombok.log.log4j2.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @lombok.extern.log4j.Log4j2 as a warning or error if configured.
lombok.log.slf4j.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @lombok.extern.slf4j.Slf4j as a warning or error if configured.
lombok.log.xslf4j.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @lombok.extern.slf4j.XSlf4j as a warning or error if configured.
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65956.html
摘要:使用方法能以簡單的注解形式來簡化代碼,提高開發人員的開發效率。能通過注解的方式,在編譯時自動為屬性生成構造器方法。出現的神奇就是在源碼中沒有和方法,但是在編譯生成的字節碼文件中有和方法。沒法實現多種參數構造器的重載。 1 Lombok背景介紹 官方介紹如下: Project Lombok makes java a spicier language by addi...
摘要:提高編碼效率使代碼更簡潔消除冗長代碼避免修改字段名字時忘記修改方法名提高下逼格以上就是的優點,當然,的優點遠遠不止以上幾點,使用,你可以更加優雅高效的編輯代碼。實戰完成了上述準備之后,就可以愉快的使用進行編碼了。接下來是使用簡化后的代碼。 Lombok介紹 近來偶遇一款擼碼神器,介紹給大家~相信許多小伙伴都深有體會,POJO類中的千篇一律的getter/setter,construct...
摘要:不久前發現有一個第三方庫可以在一定程度上幫助我們從體力勞動中解救出來,它就是。來看自動生成的方法中對于數組采用的是。檢查傳入對象是否為,若為,則拋出異常。比如自動拋受檢異常,而無需顯式在方法上使用語句。 前言 Laziness is a virtue!每當寫pojo類時,都會重復寫一些setter/getter/toString方法等大量的模版代碼,無聊繁瑣卻又不得不做,這會讓這個類變...
摘要:雖然有人可能會說里面都自帶自動生成這些方法的功能,但是使用會使你的代碼看起來更加簡潔,寫起來也更加方便。使用不使用自動生成方法使用不使用自動生成無參數構造函數。 一、lombok簡介 lombok是在學習過程中發現的一個非常好用的小工具,用了之后感覺的確很不錯,所以特此來推薦一下。 lombok的官方地址:https://projectlombok.org/ lombok的Github...
摘要:是一款在開發中簡潔化代碼十分有用的插件工具,使用注解,目的和作用就在于不用再去寫經常反復去寫的如,,等一些機械性代碼了。也可以設置不包含哪些字段使用這個注解,就不用再去手寫等方法了,注解后在編譯時會自動加進去。 lombok是一款在java開發中簡潔化代碼十分有用的插件工具,使用lombok注解,目的和作用就在于不用再去寫經常反復去寫的(如Getter,Setter,Construct...
閱讀 1410·2021-11-17 09:33
閱讀 3018·2021-10-13 09:39
閱讀 2686·2021-10-09 10:01
閱讀 2447·2021-09-29 09:35
閱讀 3891·2021-09-26 10:01
閱讀 3518·2019-08-26 18:37
閱讀 3149·2019-08-26 13:46
閱讀 1910·2019-08-26 13:39