Why use reflection? What is reflection?

Reflection can solve the problem of not knowing which object or class belongs to at compile time and only knowing the information of the object or class according to the information of program runtime. When two people are working together, all you need to know is each other’s class name to start the initial development.

The JAVA reflection mechanism allows you to know all the properties and methods of any class in the running state. For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke methods on objects is called the Reflection mechanism of the Java language.

Ii. How to use reflection from case study

public class Man implements AnimalBaseSkill{

    public int sex=-1;    
    private String name;    
    private Man(int sex, String name) {      
        this.sex = sex;        
        this.name = name;    
    }    
    public Man(a) {}public int getSex(a) {        
        return sex;    
    }    
    public void setSex(int sex) {        
        this.sex = sex;    
    }    
    public String getName(a) {        
        return name;    
    }    
    public void setName(String name) {        
        this.name = name;    
    }

    @Override
    public void eat(a) {}


    private class Clan {    
        String clanName="default family";    
        public Clan(String familyName) {        
            this.clanName = familyName;    
        }    
        public Clan(a) {}public String getClanName(a) {        
            return clanName;    
        }    
        public void setClanName(String clanName) {        
            this.clanName = clanName; }}}Copy the code
1. How do I get the Person object through reflection?
  1. Class.forname (String clazzName) Static method
  2. Calling the class attribute, person. class returns the Person’s class object (recommended).
  3. Call the getClass() method of an object

eg.

Class class1 = Class.forName("com.ch.java.reflect.Man");
Class class2 = Man.class;
Class class3 =Man.getClass();Copy the code

But only method one can get a private inner class:

Class class_clan=Class.forName("com.ch.java.reflect.Man$Clan");Copy the code

Once we get the Class, we then get the constructor through the Class to get the object using newInstance() :

Constructor constructor=class1.getConstructor(null); 
Man man= (Man) constructor.newInstance(a);Copy the code

But the object of the inner class should be obtained as follows, for reasons in (how to obtain the class constructor?) Interpretation of the

Constructor constructor=class_clan.getConstructor(Man.class.String.class);
Object family=constructor.newInstance(man, "123");Copy the code
2. How do I get the class constructor?
  1. getConstructor(Class… ParameterTypes): Returns the public constructor of the corresponding Class with the specified parameter, Connstructor
  2. GetConstructors (): Returns all public constructors of the corresponding Class of this Class object, returning the argument: Constructor[]
  3. getDeclaredConstructor(Class… ParameterTypes): Constructor[] returns the specified Constructor for this class, regardless of the Constructor’s access permissions.
  4. GetDeclaredConstructors (): Returns all constructors of the corresponding class of this class object, regardless of the Constructor’s access, with the Constructor argument: Constructor[]

The constructor of the Person object is easy to get, but how to get the constructor of the family object of the Person inner class? Where does it pit?

for (Constructor constructor1 : class_clan.getDeclaredConstructors()) {
    System.out.println(constructor1.toString()); } to print:
public com.ch.java.reflect.Man$Clan(com.ch.java.reflect.Man,java.lang.String)
public com.ch.java.reflect.Man$Clan(com.ch.java.reflect.Man)Copy the code
3. Get class member methods
  1. getMethod(String name,Class
    … ParameterTypes): returns the public Method of the corresponding class with the specified parameter. Returns Method
  2. Method[] getMethods(): Returns all public methods of the class represented by this class object
  3. Method getDeclaredMethod(string name,Class
    … ParameterTypes): returns a method with specified parameters for the corresponding class of this class object, regardless of method access rights
  4. Method[] getDeclaredMethods(): Returns all methods of the corresponding class, regardless of the access permission of the Method
class_1.getMethods();
class_1.getDeclaredMethods();
for (Method method : methods) { 
     System.out.print(method.getName()+""+method.getReturnType()+""); 
     int i=0;  
     for(Class<? > aClass : method.getParameterTypes()) { i++; System.out.print("params"+i+""+aClass.toString()+""); 
      }  
      System.out.print("\n"); } Print: getNameclass java.lang.String
setName void params1 class java.lang.String
color void params1 int
getSex int
setSex void params1 int
Disconnected from the target VM, address: '127.0.0.1:52500', transport: 'socket'wait void 
wait void params1 long params2 int
wait void params1 long
equals boolean params1 class java.lang.Object *********toString class java.lang.String 
hashCode int
getClass class java.lang.Class
notify void 
notifyAll voidCopy the code
4. Get class member variables
  1. Field getField(String name): Returns a public member variable with the specified name of the corresponding class object
  2. GetFields (): returns all public member variables of the corresponding class of this class object, and returns: Field[]
  3. GetDeclaredField (String name): Returns a member variable of the corresponding class, regardless of the access permission to the member variable. Returns the argument: Field
  4. GetDeclaredFields (): returns all member variables of the corresponding class, regardless of the access permission of the member variables, returns the argument: Field[]
Field[] fields=class_1.getFields();
Field[] fields=class_1.getDeclaredFields();
for (Field field : fields) { 
    System.out.println(field.getName()+""+field.getType()); } print: sex int age intCopy the code
5. Other

Gets the inner class of the class

Class<?>[] getDeclaredClasses(): returns thisclassAll inner classes contained in the formation corresponding classCopy the code

Gets the external class of the class object

Class<?> getDeclaringClass(): returns thisClassObject corresponds to the external class of the classCopy the code

Gets the interface implemented by the corresponding class of this class object

Class<?>[] getInterfaces(): returns thisClassObject corresponds to all interfaces implemented by the classCopy the code

Gets the parent class from which the corresponding class of the object of this class inherits

Class<? superT> getSuperclass(): returns thisClassObject corresponding to the superclass of the classClassobjectCopy the code

Gets the modifiers, packages, and class names of the corresponding classes

intGetModifiers (): Returns all modifiers for this class or interfacepublic,protected,private,final,static,abstractPackage getPackage(): Gets the Package of the CLass. String getName(): Returns the abbreviation of the CLass represented by this CLass object as a StringCopy the code

Determines whether the class is an interface, enumeration, or annotation type

booleanReturn to the isAnnotation () :classObject represents an annotation typeboolean isAnnotationPresent(Class<? extendsThe Annotation > annotationClass) : judgment hereClassWhether the object is decorated with the class AnnotationbooleanReturn to the isAnonymousClass () :classWhether the object is an anonymous classbooleanReturn to the isArray () :classObject represents an array classbooleanReturn to the isEnum () :classObject represents an enumerationbooleanIsInterface () : returns theclassObject represents an interfacebooleanIsInstance (Object obj): Checks whether obj is this ObjectclassObject, this method can be completely replacedinstanceofThe operatorCopy the code