Initial exploration of java reflection

Class class in the reflect package (note the capital C)-type identification class-Class

import java.lang.reflect;

Reflection: The ability of a program to access, detect, and modify its own state or behavior, that is, self-description and self-control.

       Can load, detect, and use classes that are completely unknown during compilation at runtime

       Can view and manipulate objects at runtime: freely create objects based on reflection, member variables that cannot be accessed by set or get, call inaccessible methods, etc.

 

That is, you can get all the information of the class through "reflection", such as

1.Field: member variable / attribute

1  class A {
 2      public  int age;
 3      private String name;
 4    
5      // constructor of A 
6      public A ( int age, String name)
 7      {
 8           this .age = age;
 9           this .name = name;
 10      }
 11  
12 A obj = new A (20, "li7an" );
 13 Class c = obj.getClass (); // Get the type ID
 14  
15  // Get all the public attributes of this class and the parent class 
16Field [] fs = c.getFields ();
 17  
18  // Get all public / protected / default / private properties declared by this class 
19 Field [] fs2 = c.getDeclaredFields ();
 20  for (Field f: f2)
 21  {
 22      f.setAccessible ( true ); // This method makes the protected / private attribute also callable, temporarily becomes public 
23 }

 

2.Method: Member method class

class B {
 public  void f1 () { 
out.println ( "B.f1 ()" ); 
} 
private String f2 (String s) { 
out.println ( "B.f2 ()" )
 return s; 
} 
B obj = new B (); 
Class c = obj.getClass (); 

// Get public method 
Method [] ms = c.getMethods ();
 for (method m: ms) {
     if ("f1" .equals (m.getName ( ))) { 
        m.invoke (obj, null ); // When calling a method in reflection, use the invoke method, at this time you must pass in an object such as "obj" here to call 
    } 
} 

//Get all methods of this class 
Method [] ms2 = c.getDeclaredMethods ();
 for (Method m: ms2) {
     if ("f2" .equals (m.getName ())) { 
        m.setAccessible ( true ); // Here again 
        String result = (String) m.invoke (obj, "abc" ); 
        out.println (result); 
    } 
}

 The m.setAccessble (true); here just temporarily turns the private / protected method into private and does not affect other objects in class B. When its new new class B object,

f2 method is still invisible

****************************************

Note: The class name.class and class name.getClass () method are the same

 

Guess you like

Origin www.cnblogs.com/li7anStrugglePath/p/12726791.html