Get member Variable information
Code and Description:
Public Static voidprintfieldmessage (Object obj) {//to get information about a class, you first get the class type of the classClass C=obj.getclass ();//The object of which child class is passed, and C is the class type of the subclass. //gets the name of the classSystem.out.println ("The name of the class is" +c.getname ()); /** The member variable is also an object * Java.lang.reflect.Field * Field class encapsulates the operation on member variables * GetFields () method gets all the Publi The member variable of c * Getdeclaredfields () Gets the information of the member variable that the class declares itself **/field[] FS=C.getdeclaredfields (); for(Field field:fs) {//the class type that gets the type of the member variableClass fieldtype=Field.gettype (); String TypeName=Fieldtype.getname (); //get the name of the member variableString fieldname=Field.getname (); System.out.println ("Member Variable:" +typename+ "" +fieldName); } }
Call this method:
Package Com.reflect; Public class ClassDemo2 { publicstaticvoid main (string[] args) { String s= "Hello"; // Classutill.printclassmessage (s); Word w=new Word (); Classutill.printfieldmessage (w); }}
Operation Result:
Get constructor information
Code and Description:
/*to print the constructor information for an object*/ Public Static voidprintconmessage (Object obj) {Class C=Obj.getclass (); /** constructor is also an object * information that encapsulates a constructor in Java.lang.Constrctor **/ //constructor[] Cs=c.getconstructors ();Constructor[] Cs=c.getdeclaredconstructors (); for(Constructor constructor:cs) {System.out.print (Constructor.getname ()+"("); //get the argument list of the constructorClass[] Paramtypes=constructor.getparametertypes (); for(Class class1:paramtypes) {System.out.print (Class1.getname ()+","); } System.out.println (")"); } }
Call:
Package Com.reflect; Public class ClassDemo2 { publicstaticvoid main (string[] args) { String s= "Hello"; // Classutill.printclassmessage (s); Word w=new Word (); // Classutill.printfieldmessage (w); Classutill.printconmessage ("Hello");} }
Results:
Java Reflection--Get member variable information