问题描述
1.HelloWorld 类:public class HelloWorld { private static HelloWorld instance = null; private HelloWorld() { } public static HelloWorld getInstance() { if (instance == null) { instance = new HelloWorld(); } return instance; } public void sayHello() { System.out.println("hello world!!"); } public static void sayHello2() { System.out.println("hello world 222 !!"); }}2.测试类:public class Test { public static void main(String[] args) throws Exception { try { Class class1 = Class.forName("com.james.HelloWorld"); Object classObject = class1.newInstance(); Method method = class1.getMethod("sayHello"); method.invoke(classObject); } catch (Exception e) { e.printStackTrace(); } }}3.运行结果报错:java.lang.IllegalAccessException: Class com.james.Test can not access a member of class com.james.HelloWorld with modifiers "private"at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)at java.lang.Class.newInstance0(Class.java:349)at java.lang.Class.newInstance(Class.java:308)at com.james.Test.main(Test.java:43)最后问题来了:这样"Object classObject = class1.newInstance();" new 一个实例肯定会出错的.现在有没有方法,通过这种反射的机制调用到"sayHello()"方法,大家帮我出出主意,先谢谢大家了.
解决方案
可以:public final class HelloWorld{ private static HelloWorld instance = null; private HelloWorld() { } public static HelloWorld getInstance() { if (instance == null) { instance = new HelloWorld(); } return instance; } public void sayHello() { System.out.println("hello world!!"); } public static void sayHello2() { System.out.println("hello world 222 !!"); } static class Test { public static void main(String[] args) throws Exception { try { Class class1 = Class.forName("HelloWorld"); Constructor[] constructors = class1.getDeclaredConstructors(); AccessibleObject.setAccessible(constructors, true); for (Constructor con : constructors) { if (con.isAccessible()) { Object classObject = con.newInstance(); Method method = class1.getMethod("sayHello"); method.invoke(classObject); } } } catch (Exception e) { e.printStackTrace(); } } }}effective java中第三条就说了这种方式。还强调枚举才是单例的王道。