var x=10.0; 将推断double; var y=new arraylist(); 将推断Arraylist; 注意:
对于复合类型,推断出最常见的父类,而不是接口。例如,bool ? new HashSet() : new ArrayList()是一个带有复合类型的表达式.存在同样的父类:AbstractCollection,也实现了同样的接口:Serializable。最终推断的类型将是AbstractCollection,因为它是一个类,而Serializable是接口。 在不明确的情况下,例如当初始化表达式是null,将推断为java.lang.Object 这是一个注释类型,因为var x=10;将被解语法糖为@var int x=10; 注意:var 和 val 具有完全相同的语义,只是val变成@val 但是推荐使用val,因为idea具有val自带的postfix template:
//使用示例
public String example() {
val example = new ArrayList();
example.add("Hello, World!");
val foo = example.get(0);
return foo.toLowerCase();
}
public class DataExample {
@NonNull private String name;
}
编译后的class为:
public class DataExample {
public DataExample(@NonNull String name) {
if (name == null)
throw new NullPointerException("name is marked non-null but is null");
this.name = name;
}
public void setName(@NonNull String name) {
if (name == null)
throw new NullPointerException("name is marked non-null but is null");
this.name = name;
}
}
@RequiredArgsConstructor : 生成一个包含 “特定参数” 的构造器,特定参数指的是那些有加上 final 修饰词的变量们或者加了@NonNull注解的参数。如果指定staticName = "of"参数,还会生成一个返回类对象的静态工厂方法。
如下例:
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample {
private int x, y;
@NonNull private T description;
private final String finalString;
@NoArgsConstructor
public static class NoArgsExample {
@NonNull private String field;
}
}
经过编译后,class文件反编译,实际的类文件等同于:
public class ConstructorExample {
private int x;
private int y;
@NonNull
private T description;
private final String finalString;
private ConstructorExample(@NonNull T description, String finalString) {
if (description == null)
throw new NullPointerException("description is marked non-null but is null");
this.description = description;
this.finalString = finalString;
}
public static ConstructorExample of(@NonNull T description, String finalString) {
return new ConstructorExample<>(description, finalString);
}
protected ConstructorExample(int x, int y, @NonNull T description, String finalString) {
if (description == null)
throw new NullPointerException("description is marked non-null but is null");
this.x = x;
this.y = y;
this.description = description;
this.finalString = finalString;
}
public static class NoArgsExample {
@NonNull
private String field;
}
}
这里注意一个 Java 的小坑,当我们没有指定构造器时,Java 编译器会帮我们自动生成一个没有任何参数的构造器给该类,但是如果我们自己写了构造器之后,Java 就不会自动帮我们补上那个无参数的构造器了,然而很多地方(像是 Spring Data JPA),会需要每个类都一定要有一个无参数的构造器,所以你在加上 @AllArgsConstructor 时,一定要补上 @NoArgsConstrcutor,不然会有各种坑等着你。
@ToString(exclude="id")
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
private int id;
@ToString(callSuper=true, includeFieldNames=true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
}
经过编译后,class文件反编译,实际的类文件等同于:
public class ToStringExample {
private int id;
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
public String toString() {
return "ToStringExample(name=" + getName() + ", shape=" + this.shape + ", tags=" + Arrays.deepToString((Object[])this.tags) + ")";
}
public static class Square extends Shape {
private final int width;
private final int height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
public String toString() {
return "ToStringExample.Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
}
}
}
也是整合包,但是他会把所有的变量都设成 final 的,其他的就跟 @Data 一样,等于同时加了以下注解:@ToString,@EqualsAndHashCode,@AllArgsConstructor,@FieldDefaults,@Getter。
所有字段由private和final修饰,不会产生setter方法。类本身也是由final修饰。
创建Lombok示例如下:
@Value public class ValueExample {
String name;
@NonFinal
int age;
double score;
protected String[] tags;
@ToString(includeFieldNames=true)
@Value(staticConstructor="of")
public static class Exercise {
String name;
T value;
}
}
经过编译后,class文件反编译,实际的类文件等同于:
public final class ValueExample {
private final String name;
private int age;
private final double score;
protected final String[] tags;
public ValueExample(String name, int age, double score, String[] tags) {
this.name = name;
this.age = age;
this.score = score;
this.tags = tags;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof ValueExample))
return false;
ValueExample other = (ValueExample)o;
Object this$name = getName(), other$name = other.getName();
return ((this$name == null) ? (other$name != null) : !this$name.equals(other$name)) ? false : ((getAge() != other.getAge()) ? false : ((Double.compare(getScore(), other.getScore()) != 0) ? false : (!!Arrays.deepEquals((Object[])getTags(), (Object[])other.getTags()))));
}
public int hashCode() {
int PRIME = 59;
result = 1; //不知道为什么反编译class会是这样的写法
Object $name = getName();
result = result * 59 + (($name == null) ? 43 : $name.hashCode());
result = result * 59 + getAge();
long $score = Double.doubleToLongBits(getScore());
result = result * 59 + (int)($score >>> 32L ^ $score);
return result * 59 + Arrays.deepHashCode((Object[])getTags());
}
public String toString() {
return "ValueExample(name=" + getName() + ", age=" + getAge() + ", score=" + getScore() + ", tags=" + Arrays.deepToString((Object[])getTags()) + ")";
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public double getScore() {
return this.score;
}
public String[] getTags() {
return this.tags;
}
public static final class Exercise {
private final String name;
private final T value;
public String toString() {
return "ValueExample.Exercise(name=" + getName() + ", value=" + getValue() + ")";
}
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 boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Exercise))
return false;
Exercise> other = (Exercise)o;
Object this$name = getName(), other$name = other.getName();
if ((this$name == null) ? (other$name != null) : !this$name.equals(other$name))
return false;
Object this$value = getValue(), other$value = other.getValue();
return !((this$value == null) ? (other$value != null) : !this$value.equals(other$value));
}
public int hashCode() {
int PRIME = 59;
result = 1; //不知道为什么反编译class会是这样的写法
Object $name = getName();
result = result * 59 + (($name == null) ? 43 : $name.hashCode());
Object $value = getValue();
return result * 59 + (($value == null) ? 43 : $value.hashCode());
}
public String getName() {
return this.name;
}
public T getValue() {
return this.value;
}
}
}
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;
}
}
//经过编译,相当于以下这个class
public class GetterLazyExample {
private final AtomicReference cached = new AtomicReference();
public double[] getCached() {
Object value = this.cached.get();
if (value == null)
synchronized (this.cached) {
value = this.cached.get();
if (value == null) {
double[] actualValue = expensive();
value = (actualValue == null) ? this.cached : actualValue;
this.cached.set(value);
}
}
return (value == this.cached) ? null : (double[])value;
}
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++)
result[i] = Math.asin(i);
return result;
}
}
@Cleanup(“dispose”) CoolBar bar = new CoolBar(parent, 0); 如Lombok示例:
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);
}
}
}
经过编译后,class文件反编译,实际的类文件等同于:
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();
}
}
}
}