@Data
@Builder
@ToString
public class Reflect implements Cloneable{
public String name ;
public String age ;
static {
System.out.println("Reflect靜態塊");
}
public Reflect() {
System.out.println("Reflect構造");
}
public Reflect(String name,String age) {
this.age =age;
this.name=name;
}
@Override
protected Object clone() {
Reflect reflect = null;
try {
reflect = (Reflect) super.clone();
return reflect;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
public static void main(String[] args) {
// 不會初始化靜態塊
System.out.println("clazz1:------");
Class clazz1 = Reflect.class;
System.out.println("clazz2:------");
// 會初始化
try {
Class clazz2 = Class.forName("com.rainbow.dp.Base.Reflect");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("clazz3:------");
try {
Class clazz3 = Class.forName("com.rainbow.dp.Base.Reflect");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Reflect clazz4 = Reflect.builder().age("16").name("na").build();
Reflect clazz5 =(Reflect) clazz4.clone();
}
執行結果ide
clazz1:------
clazz2:------
Reflect靜態塊
clazz3:------
Reflect構造
以上代碼總結兩點:函數
能夠看出靜態函數在運行時只加載一次ui
Class.forName 會調用靜態塊
Reflect.class 不會調用靜態塊