Java--reflect reflection mechanism

Source: Internet
Author: User

  • The use of class classes
    • In the world of OOP, everything is object. Whose object is the class? --The class is an object, and the class is an instance object of the Java.lang.Class class! there is a class named class.
    • Instance:
    • //there is a class ofclassFoo {voidPrint () {System.out.println ("Foo"));} }//in the main function: Public Static voidMain (string[] args) {//Foo This class is also an instance object, the Class class instance object, how to express it//Any class is an instance object of class, and this instance object is represented in three ways//1.--actually tells us that any class has an implicit static member variable-classClass C1 = Foo.class; //2. Objects of this class are known to pass the GetClass methodFoo F1 =NewFoo (); Class C2=F1.getclass (); //C1, C2 represents the class type of the Foo class ( class type)//A class is also an object, an instance object of class, which becomes the class type of the class.//whether from C1,C2 represents the class type of the Foo class, a class can only be an instance object of classSYSTEM.OUT.PRINTLN (C1 = = C2);//true//3.Class C3 =NULL; Try{C3= Class.forName ("Com.immoc.reflect.Foo"); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (C3= = C2);//true        /** We can create an object instance from the class type of the class; * Create an object of the Foo class by C1 or C2 or C3*/        Try{foo Foo= (Foo) c1.newinstance ();//requires an argument-free construction methodFoo.print (); } Catch(instantiationexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }    
      View Code
    • Dynamic load classes: For example, Class.forName ("Full name of the class") not only represents the class type of the class, but also represents the dynamic load class
      • Compile time load class is static load class, runtime load class is dynamically loaded
      • The new object is a statically loaded class that needs to load all the classes that may be used at compile time
      • Dynamic load classes:
        • Class C = class.forname (Args[0]);
        • Officeable OA = (officeable) c.newinstance (); To create an object instance of this class from a class type
      • Functional classes use dynamic loading as much as possible, rather than static loading
    • Basic data type, void keyword exists class type
    • Basic API operations for class classes
    • /*** Print class information, including member functions of the class, member variables *@paramobj*/     Public Static voidprintclassmessage (Object obj) {//to get information about a class, you first get the class type of the classClass C = Obj.getclass ();//The object of which subclass is passed, and C is the class type of the classSystem.out.println ("The name of the class is:" +c.getname ()); /** Methods Class, Method Object * A member method is a Methods object * the GetMethod () method obtains all public functions, including those inherited by the parent class .*/method[] Ms=C.getmethods ();  for(Method m:ms) {//gets the class type of the method return value typeClass ReturnType =M.getreturntype (); System.out.print (Returntype.getname ()+ " "); System.out.print (M.getname ()+ "("); //get parameter Type--Get the class type of the type of the parameter listclass[] Paramtypes =m.getparametertypes ();  for(Class p:paramtypes) {System.out.print (P.getname ()+ ","); } System.out.println (")"); }    }
      View Code

  • Reflection of the method
    •  Public Static voidprintmethodmessage (Object obj) {//to get information about a class, you first get the class type of the classClass C = Obj.getclass ();//The object of which subclass is passed, and C is the class type of the classSystem.out.println ("The name of the class is:" +c.getname ()); /** Methods Class, Method Object * A member method is a Methods object * the GetMethod () method obtains all public functions, including those inherited by the parent class .*/method[] Ms=C.getmethods ();  for(Method m:ms) {//gets the class type of the method return value typeClass ReturnType =M.getreturntype (); System.out.print (Returntype.getname ()+ " "); System.out.print (M.getname ()+ "("); //get parameter Type--Get the class type of the type of the parameter listclass[] Paramtypes =m.getparametertypes ();  for(Class p:paramtypes) {System.out.print (P.getname ()+ ","); } System.out.println (")"); }    }
      View Code

    • How to get a method
      • The name of the method and the parameter list of the method can only determine a method
    • Action reflected by the method
      • Method.invoke (object, parameter list)
      •  Public classMethodDemo1 { Public Static voidMain (string[] args) {/** To get the print (int, int) method * First get information about the class (class information of Class)*/A A1=NewA (); Class C=A1.getclass (); //2. Get the method, name and argument list        Try{Method m= C.getdeclaredmethod ("Print",Newclass[]{int.class,int.class}); //Method Reflection Operation: Invoking a method with an objectM.invoke (A1,NewOBJECT[]{10, 20}); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }             }}classA { Public voidPrintintAintb) {System.out.println (a+b); }     Public voidPrint (String A, string b) {System.out.println (A.touppercase ()+ "," +b.tolowercase ()); }}
        View Code

  • Reflection of member variables
    • Member variables are also objects, Java.lang.reflect.Field, Field classes encapsulate operations on member variables
    • The GetFields () method gets the information for all public member variables
    • Getdeclaredfields () Gets the information for all member variables declared by the class itself
    • //first get the type, and then get the name of the variable://such as: private int t; Public Static voidprintfieldmessage (Object obj) {System.out.println ("---------------------------------------------"); Class C=Obj.getclass (); Field[] FS=C.getdeclaredfields ();  for(Field f:fs) {//the class type that gets the type of the member variable: intClass FieldType =F.gettype (); String TypeName=Fieldtype.getname (); //get the name of the member variable: TString FieldName =F.getname (); System.out.println ("TypeName:" + typeName + "FieldName:" +fieldName); }    }
      View Code

  • Reflection of the constructor function
    • /*** Print constructor information (constructor is also object: java.long.Constructor) *@paramobj*/     Public Static voidprintconmessage (Object obj) {Class C=Obj.getclass (); Constructor[] CS=c.getdeclaredconstructors ();  for(Constructor con:cs) {System.out.print (Con.getname ()+ "("); //Get parameter listclass[] Paramtypes =con.getparametertypes ();  for(Class cl:paramtypes) {System.out.print (Cl.getname ()+ ","); } System.out.println (")"); }    }
      View Code

  • Java class loading mechanism
  • Understanding the nature of set generics through reflection
    • Generics in a collection in Java are prevented from being entered incorrectly, only in the compile phase, and not after compilation. Validation: Reflection by method
    •  Public Static voidMain (string[] args) {//TODO auto-generated Method StubArrayList L1 =NewArrayList (); ArrayList<String> L2 =NewArraylist<string>(); L1.add ("Hello"); L1.add (2);//wrong? Is it related to the JDK version??? Class C1 =L1.getclass (); Class C2=L2.getclass (); SYSTEM.OUT.PRINTLN (C1= = C2);//true to explain that the generics of the compiled collection are de-generalized//reflected operations are post-compilation operations                Try{Method m= C2.getmethod ("Add", Object.class); M.invoke (L1,"World");        System.out.println (L1.size ()); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }     }
      View Code

Application: The name of the class is used to produce an object such as: integer in = (integer) class.forname (className). newinstance ();

Java--reflect reflection mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.