在Java中,在拿到类对象的Class后,就可以通过Java的反射机制来创建类对象的实例对象了,主要分为以下几种方式:
- Class.newInstance()
- 调用类对象的构造方法
但是,如果需要被反射的类是单例呢?若使以上两种方式,则每次都会重新构造一个不同的实例。
此时我们可以利用Class.getDeclaredMethod直接获取单例获取方法,然后invoke就可以了。
单例类
package ewhine.models;
import java.lang.reflect.Method;
public class SingletonReflection {
private SingletonReflection() {}
public static SingletonReflection getInstance() {
return SingletonHolder.instance;
}
private static class SingletonHolder {
public static final SingletonReflection instance = getInstance();
private static SingletonReflection getInstance() {
return new SingletonReflection();
}
}
public void say() {
System.out.println("hello singleton");
}
}
关键是如下代码
Class c = Class.forName("ewhine.models.SingletonReflection");
Method m = c.getDeclaredMethod("getInstance", null);
SingletonReflection singletonReflection = (SingletonReflection) m.invoke(null, null);
测试
public static void main(String[] args) {
try {
Class c = Class.forName("ewhine.models.SingletonReflection");
Method m = c.getDeclaredMethod("getInstance", null);
SingletonReflection singletonReflection = (SingletonReflection) m.invoke(null, null);
singletonReflection.say();
((SingletonReflection) c.newInstance()).say();
System.out.println(m.invoke(null) == m.invoke(null, null));
System.out.println(c.newInstance() == c.newInstance());
} catch (Throwable t) {
t.printStackTrace();
}
}
输出
hello singleton
hello singleton
true
false