package cn.pb.constructor;import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;public class Main {
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
Class cla=Calendar.class;
Calendar cal=(Calendar) cla.newInstance();
System.out.println(cal.toString());
}
}运行时抛出java.lang.IllegalAccessException异常,求高手解答。

解决方案 »

  1.   

    protected  Calendar() 
     
      

  2.   

    package cn.pb.constructor;import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Calendar;public class Main {
    public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
    Class cla=Calendar.class;

    Constructor cons=cla.getConstructor();

    cons.setAccessible(true);
    Calendar cal=(Calendar) cons.newInstance();
    System.out.println(cal.toString());
    }
    }
    还是不行,这个问题很头痛,Constructor cons=cla.getConstructor();
    我也换成过Constructor cons=cla.getDeclaredConstructor();
    也是不行。
      

  3.   


    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.Calendar;public class Main {
        public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
         Class cla=Calendar.class;
            Method m= cla.getMethod("getInstance", null);
            Calendar calendar = (Calendar) m.invoke(cla, null);
            System.out.println(calendar.toString());
            
        }
    }
    由于Calendar的构造函数是protected所以是无法外部类访问他的构造函数的,故无法new出实例,你可以通过反射调用它的getInstance方法得到实例
      

  4.   

    e...
    我的意思是 你不能去newInstance一个非public的类构造器。