饿汉试单例模式
public class HelloWorld {
private HelloWorld(){};
private static HelloWorld hell = new HelloWorld();
public static HelloWorld getHello(){
return hell;
}
public void getWorld(){
System.out.println("hahahahah");
}
}
java反射机制 调用getWorld()方法
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class HelloJava{
public static void main(String[] args){
/* HelloWorld hell = HelloWorld.getHello();
hell.getWorld();*/
try
{
Class class1 = Class.forName("cn.jr.text.HelloWorld");
Constructor[] constructors = class1.getDeclaredConstructors();
AccessibleObject.setAccessible(constructors, true);
for (Constructor con : constructors)
{
if (con.isAccessible())
{
Object classObject = con.newInstance();
Method method = class1.getMethod("getWorld");
method.invoke(classObject);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}