1 PackageCom.gh.ref;2 3 Public classPerson {4 PrivateString name;5 Private intAge ;6 Private Charsex;7 Private voidsay () {8System.out.println ("I am" +name);9 }Ten PublicString GetName () { One returnname; A } - Public voidsetName (String name) { - This. Name =name; the } - Public intGetage () { - returnAge ; - } + Public voidSetage (intAge ) { - This. Age =Age ; + } A Public CharGetsex () { at returnsex; - } - Public voidSetsex (Charsex) { - This. Sex =sex; - } - PublicString toString () { in return"Person [name=" + name + ", age=" + Age + ", sex=" + Sex + "]"; - } to PublicPerson (String name,intAgeCharsex) { + Super(); - This. Name =name; the This. Age =Age ; * This. Sex =sex; $System.out.println ("Call person has a constructor method");Panax Notoginseng } - PublicPerson () { the Super(); +System.out.println ("Call person without parameter construction method"); A } the +}
1 PackageCom.gh.ref;2 ImportJava.lang.reflect.Constructor;3 ImportJava.lang.reflect.Field;4 Importjava.lang.reflect.InvocationTargetException;5 ImportJava.lang.reflect.Method;6 ImportJava.lang.reflect.Modifier;7 /**8 * Reflection9 * @authorGanhangTen */ One Public classRefdemo { A Public Static voidMain (string[] args)throwsException { -Person p=NewPerson ("small white", 18, ' Male '); -Person p1=NewPerson ("Little black", 10, ' female '); the //Create Class object method one -Class personclass=P.getclass (); -Class personclass1=P1.getclass (); -System.out.println (personclass==personClass1); + /** - * True because the Java Virtual machine first loads Person.class through the ClassLoader into memory, which is loaded into memory as a class type + * But two objects load only one person at a time, so their memory address is the same; this is the same as instanceof's function . A */ at //To Create a Class object method two -Class Personclass3=person.class;//A Class object represents a byte code, and the same type of object has the same bytecode. -System.out.println (personclass3==personClass1); - //Int.class; - //Void.class; - //To Create a Class object method three inClass personclass4=class.forname ("Com.gh.ref.Person");//may not be able to find the class to throw exceptions, pay attention to the package name -System.out.println (personclass4==personClass1); to //--------Instantiate objects through class information-------- + //call the No-argument construction method - Person P3; the Try { *P3 =(person) personclass4.newinstance (); $SYSTEM.OUT.PRINTLN (p3);//because no argument constructs are called, they are all empty, and if there is no parameterless construction method in the class, the exception will be reported.Panax Notoginseng}Catch(Instantiationexception |illegalaccessexception E1) { - e1.printstacktrace (); the } + //calling a method with a parameter constructor AConstructor[] cons= personclass4.getconstructors ();//get the current class so the construction method thePerson p4=NULL; + Try { - //the class object that passes the specified argument $Constructor C=personclass4.getconstructor (String.class,int.class,Char.class); $p4= (person) c.newinstance ("Floret", 18, ' female '); - System.out.println (p4); -}Catch(Exception e) { the e.printstacktrace (); - }Wuyi //----------Obtain class information by class------- theSYSTEM.OUT.PRINTLN ("Package Information:" +personclass.getpackage (). toString ());//returns a package class -System.out.println ("Class name:" +personclass.getname ()); Wu //Get method information for a class -Method[] Ms=personclass.getmethods (); About /** $ * Returns an array that contains some Method objects. - * These objects reflect the class or interface represented by this class object - * (including those classes or interfaces that are declared by the class or interface and those that inherit from the superclass and the hyper-interface) are public member methods - * If you can use Getdeclaredmethods () as long as you define methods (including private) for this class A */ + for(Method m:ms) { the //The Get access modifier returns a number that requires modifier to go -System.out.println ("Method name" +modifier.tostring (M.getmodifiers ()) + "-" +m.getname ()); $ } the //Gets the property information for the class, Getdeclaredfields () gets the private theField[] Fs=personclass.getfields ();//public attribute, person does not have the for(Field f:fs) { theSystem.out.println ("Property name:" +f.getname ()); - } inSystem.out.println ("---------Call method--------"); the Try { theMethod M=personclass4.getmethod ("SetName", String.class); AboutM.invoke (P4, "floral"); the System.out.println (p4); the //if the private method is called say theMethod M1=personclass4.getdeclaredmethod ("say");//Note how you can tune a private method +M1.setaccessible (true);//Ignore validation modifiers to make them visible to the outside - M1.invoke (p4); the}Catch(Exception e) {Bayi e.printstacktrace (); the } theSystem.out.println ("---------Call Property--------"); -Field Agef=personclass4.getdeclaredfield ("Age"); -Agef.setaccessible (true);//Ignore validation modifiers theSystem.out.println (Agef.get (p4));//getting the age of P4 theAgef.setint (P4, 11);//set the age value for P4 the System.out.println (p4); the } -}
The reflection of learning in Java