1 PackageCom.study.reflect;2 3 ImportJava.lang.reflect.Constructor;4 Importjava.lang.reflect.InvocationTargetException;5 6 /**7 * The constructor is reflected through the class. 8 * @ClassName: Constructordemo9 * @authorBluelakeTen * @date August 13, 2015 PM 5:16:07 One */ A Public classConstructordemo { - - Public Static voidMain (string[] args)throwsnosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException { the -Class C = Student.class; - - //getconstructors () Public decoration construction Method +Constructor[] Cons =c.getconstructors (); - for(Constructor con:cons) { + System.out.println (con); A /* at * Public com.study.reflect.Student (java.lang.string,int) - Public com.study.reflect.Student () - */ - } - -System.out.println ("---------------------------------"); in - //getdeclaredconstructors () includes private methods toconstructor[] Cons2 =c.getdeclaredconstructors (); + for(Constructor con:cons2) { - System.out.println (con); the /* * * Private Com.study.reflect.Student (java.lang.String) $ Public com.study.reflect.Student (java.lang.string,int)Panax Notoginseng Public com.study.reflect.Student () - */ the } +SYSTEM.OUT.PRINTLN ("------****************-----------"); A //gets the constructor for the specified argument theConstructor one = C.getconstructor (int.class); +System.out.println (one);//Public com.study.reflect.Student (int) -class[] CLS =one.getparametertypes (); $ for(Class cl:cls) { $SYSTEM.OUT.PRINTLN (CL);//int -System.out.println (Cl.getname ());//int -System.out.println (Cl.getsimplename ());//int the } - WuyiConstructor-C.getdeclaredconstructor (String.class,int.class); theclass[] Cls2 =two.getparametertypes (); - for(Class cl:cls2) { Wu //Output class ID and class full name. -SYSTEM.OUT.PRINTLN (CL);//class Java.lang.String About //the class name of the output parameter $System.out.println (Cl.getname ());//java.lang.String - //class simplified name for output parameters -System.out.println (Cl.getsimplename ());//String - } A + //to get the constructor by a parameter array theClass[] params =NewClass[2]; -Params[0] = String.class; $PARAMS[1] =int.class; theConstructor three =C.getdeclaredconstructor (params); the the the /** - * Create an object by using the obtained constructor in */ theObject Objone = one.newinstance (18); the if(ObjoneinstanceofStudent) { AboutStudent stu =(Student) Objone; the System.out.println (Stu.getage ()); the } the +Object objtwo = two.newinstance ("Xiang Yu", 27); - if(ObjtwoinstanceofStudent) { theStudent stu =(Student) objtwo;BayiSystem.out.println (Stu.getname () + "..." +stu.getage ());//Xiang Yu ... - the } the -Object Objthree = three.newinstance ("Caocao", 56); - if(ObjthreeinstanceofStudent) { theStudent stu =(Student) objthree; theSystem.out.println (Stu.getname () + "..." +stu.getage ());//The Devil ... about the } the } -}
Java Reflection "II" get the constructor