请说明方案和理由
创建一个类的时候一定会调用该类的构造方法,不知道你说的实例块是什么
http://blog.csdn.net/mhmyqn/article/details/7943411
实例块是在构造器调用之前调用的,而且是每new一个实例就调用一次。
对于这段代码
public class Test {
{
System.out.println("abcd");
}
Test(int i) {
System.out.println(i);
}
Test(int i, long j) {
System.out.println(i + j);
}
}
查看字节码:
可以看到,在代码编译成为class文件时,实例代码块就被加入到了构造方法的前部,可以保证实例代码块是一定会被执行的。
public class TestMain {
private static Unsafe unsafe = null;
static {
init();
}
public static void main(String[] args) {
getInstance(A.class);
}
@SuppressWarnings("restriction")
private static synchronized void init() {
if (unsafe != null) {
return;
}
Field f = null;
try {
f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(null);
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "unchecked", "restriction" })
public static final <T> T getInstance(Class<T> clazz) {
T t = null;
if (unsafe != null) {
try {
t = (T) unsafe.allocateInstance(clazz);
} catch (InstantiationException e) {
e.printStackTrace();
}
}
return t;
}
class A {
private final int a;
{
System.out.println("a");
}
public A(int a) {
this.a = a;
}
public int getA() {
return a;
}
}
}
通过unsafe进行对象实例化,首选绕过了A的构造器创建对象,对a也不需要赋值操作。