1 Packagecn.itcast_02;2 3 ImportJava.lang.reflect.Constructor;4 5 /*6 * Requirements: Get private construction methods through reflection and use7 * Private person (String name) {}8 * 9 * Person p = new Person ("Wind Qing");Ten * SYSTEM.OUT.PRINTLN (p); One */ A Public classReflectDemo3 { - Public Static voidMain (string[] args)throwsException { - //Get bytecode File object theClass C = class.forname ("Cn.itcast_01.Person"); - - //get Private Constructor Method object - //Nosuchmethodexception: Each of these methods is abnormal + //The reason is that the method we used at the beginning can only get public, and this is the way to do it. -Constructor con = c.getdeclaredconstructor (String.class); + A //create an object with this private construction method at //illegalaccessexception: illegal access exception. - //Violent visits -Con.setaccessible (true);//A value of TRUE indicates that the reflected object should cancel the Java language Access check when it is used. -Object obj = con.newinstance ("Wind"); - - System.out.println (obj); in } -}
Android (Java) Learning Note 108: Get private construction methods through reflection and use