Java Reflection mechanism is in the running state , for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language.
1.
Class cls1 = Role.class; ///////
Class cls2 = Class.forName ("Yui. Role ");///////
Two ways to get class.
2.
- Public constructor<?>[] GetConstructors () returns all the public constructor collections in the class, with the default constructor subscript 0
- Public constructor<t> getconstructor (class<?> ... parametertypes) returns the specified public constructor, which is a constructor parameter type collection
- Public constructor<?>[] Getdeclaredconstructors () returns all constructors in the class, including private
- Public constructor<t> getdeclaredconstructor (class<?> ... parametertypes) returns any specified constructor
Methods of several constructors.
Instance:
String ss=NewString ("FFF"); Class C1=Ss.getclass (); UKF U1=NewUKF (); Try{Object o=c1.newinstance (); //u1= (UKF) o;}Catch(instantiationexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(illegalaccessexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Try{Constructor con=class.forname ("C.UKF"). GetConstructor (); Object o=con.newinstance (); U1=(UKF) o; } Catch(nosuchmethodexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(SecurityException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(ClassNotFoundException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(instantiationexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); } u1.show (); Try{Class C2=class.forname ("C.UKF"); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }
Java Reflection mechanism