Summary of Java Reflection

Source: Internet
Author: User
Tags modifier modifiers

Reflection (Java.lang.reflect) for analyzing class capabilities

A Class 1. Definition

The Java runtime maintains a type identity for each object that the class that the object belongs to provides to the virtual machine analysis call, and the class that holds the information is the classes

(A class class object can be understood as a type, which can be a class or base data type int, etc.)

2. Role

With the class class that the object belongs to, we can get the data field of the object type, the method, the parent class and so on, and can also use it to create the instance object

Get parent class

            // 2. Get the parent class            Class Superc1=c1.getsuperclass ();

Create an instance

        // creating an Instance object        with Reflection Class myclass=class.forname ("Java.util.Random");        Random random= (random) myclass.newinstance ();    
3.3 Ways to get class

static method of calling Class gets: Class.forName (String className)

Object calls the GetClass () method to get the class

Obtained through the type name. class, such as T.class,t can be a basic data type int, or it can be a specific class such as Random.class

        Class myclass=class.forname ("Java.util.Random");        MyClass=new  Random (). GetClass ();        MyClass=random. class;

(ii) The three classes used to describe a class: Field,method,constructor

The field class represents a data field in a class

Method class represents an approach in a class

The constructor class represents a constructor in a class

All three of these classes inherit accessible

1. Get the Field,method,constructor in a class

The class class calls the Getdeclaredfields () method to get all the data fields of the class

The class class calls the Getdetclaredmethods () method to get all the methods of the class

The class class calls the Getdetclaredconstructors () method to get the constructor

2. Get a class| field| method| Modifier for constructor
            // modifier.tostring () to get the C1 modifier public final            String modifiers=modifier.tostring (C1.getmodifiers ());        

Calling the GetModifiers () method of these four classes can return an int, passed in as a parameter to Modifier.tostring (), which will determine the modifier based on int

3. Get the field data field type (Class) and Field Ming Chen
            Class classtype=f.gettype ();            String name=f.getname ();
4. Get the return type of method, method name, method parameter type
            String returntype=Methods[j].getreturntype (). GetName ();            String methodName=methods[j].getname ();            Class[] paratypes=methods[j].getparametertypes ();
5. Print specific information for a class
 PackageReflect;ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Modifier;/*** @ClassName reflectiontest * @Description use reflection to print all methods of the double class * @Author Cherry * @Date 2018/6/9 21:22 * @Update 2018 /6/9 21:22 **/ Public classreflectiontest{ Public Static voidMain (string[] argv) {String className= "Java.lang.Double"; Try{            //1. Get the classClass c1=Class.forName (className); //2. Get the parent classClass superc1=C1.getsuperclass (); //3.modifier.tostring () to get the properties of C1 public finalString modifiers=modifier.tostring (C1.getmodifiers ()); //4. Print the properties of the C1            if(Modifiers.length () >0) System.out.print (modifiers+ ""); //5. Print the class name of the C1System.out.print ("class" +className); //6. Print If there is inheritance            if(superc1!=NULL&&superc1!=object.class) System.out.print ("extends" +superc1.getname ()); //7. Print the bracketsSystem.out.print ("\n{\n"); //8. Print FieldsPrintfields (C1); //9. Print BuilderPrintconstructors (C1); //10. Printing methodsPrintmethods (C1); //11. Print the bracketsSystem.out.print ("\n}\n"); }Catch(ClassNotFoundException e) {e.printstacktrace (); }    }    /*** Print field *@paramC1*/     Public Static voidPrintfields (Class C1) {//1. Get all DomainsField[] Fields=C1.getfields (); //2. Traverse the print         for(Field f:fields) {Class ClassType=F.gettype (); String name=F.getname (); //3. Print a carry characterSystem.out.print (""); //4. Print PropertiesString modifiers=modifier.tostring (F.getmodifiers ()); if(Modifiers.length () >0) System.out.print (modifiers+ ""); System.out.println (ClassType+ "" +name+ ";");    } System.out.println (); }    /*** Print constructors for incoming classes *@paramC1*/     Public Static voidprintconstructors (Class C1) {//1. Get all constructorsConstructor[] Constructors=c1.getconstructors (); //2. Traverse the print         for(Constructor c:constructors) {//3. Print tab PlaceholdersSystem.out.print (""); //4. Get the properties of a constructorString modifier=modifier.tostring (C.getmodifiers ()); if(Modifier.length () >0) System.out.print (modifier+ ""); //5. Print the constructor nameString conname=C.getname (); System.out.print (ConName+"("); //6. Printing parametersClass[] Paratypes=c.getparametertypes ();  for(intj=0;j<paratypes.length;j++){                if(j>0) System.out.print (",");            System.out.print (Paratypes[j].getname ()); } System.out.print ("); \ n"); } System.out.print ("\ n"); }    /*** Printing method *@paramC1*/     Public Static voidPrintmethods (Class C1) {//1. Get all the methodsMethod[] Methods=C1.getmethods (); //2. Traverse the print         for(intj=0;j<methods.length;j++){            //3. Print placeholdersSystem.out.print (""); //4. Printing Method PropertiesString modifiers=modifier.tostring (Methods[j].getmodifiers ()); if(Modifiers.length () >0) System.out.print (modifiers+ ""); //5. Print return typeString returntype=Methods[j].getreturntype (). GetName (); System.out.print (ReturnType+" "); //6. Printing method NameString methodname=Methods[j].getname (); System.out.print (MethodName+"("); //7. Print parameter namesClass[] Paratypes=methods[j].getparametertypes ();  for(inti=0;i<paratypes.length;i++){                if(i>0) System.out.print (",");            System.out.print (Paratypes[i].getname ()); }            if(j+1!=methods.length) System.out.print (") \ n"); }    }}
(iii) The runtime gets the specific value of the data field of an object
        Student student=New Student ();                        // Create a Student object        Class Studentclass=student.getclass ();                  // get student's class        Field Field=studentclass.getdeclaredfield ("Age");       // get the Age domain        Field.setaccessible (true);                              // settings to access private domain        System.out.println (Field.get (student));                 // accessing the value of an age domain
(iv) method of invoking an object
        Student student=New Student ();   // Create a Student object        Class Studentclass=student.getclass ();                  // get student's class        int. class);     // Get method        Setagemethod.invoke (student,20);                       // Accessing the value        of an age domain System.out.println (Student.getage ());                         // return                         
(v) Implementing a generic array operation method
    /*** Used to extend an already filled array *@paramA *@paramNewlength *@return     */     Public StaticObject Goodcopyof (Object A,intnewlength) {Class C1=a.getclass ();//gets the class of the incoming a        if(!c1.isarray ())return NULL;//If the array type is not directly returned nullClass Compomenttype=c1.getcomponenttype ();//get array element type        intLength=array.getlength (a);//gets the length of the passed-in arrayObject newarray=array.newinstance (compomenttype,newlength);//array.newinstance () creates a new array of the same type based on the element type and length and extends the lengthSystem.arraycopy (A,0,newarray,0,math.min (length,newlength));//assigns the value of the original array to the new array        returnNewArray; }

Refer to "Java Core Technology Volume I" p190

Summary of Java Reflection

Related Article

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.