Java learning Summary - reflection

Reflection often hear the word, but do not always understand what it means. Today we look to understand the concept of reflection, why in the framework design, the reflector used more. This article documents the knowledge about the learning aspects of reflection.

Concept of reflection

JAVA reflection mechanism is in the operating state, for any class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; this information acquired dynamically and dynamic invocation a method of object function called reflection mechanism java language. Concept is more accurate, but does not facilitate an understanding of the abstract. For example, we present a class, its associated properties, methods, type of constructor is private, for such a class, we can not create a new way to its target, but not by the usual method using the property way to invoke this class properties, methods, and even to create its objects, but it can be generated in this way by reflecting object and call its properties and methods.

Class

Class and class are essentially different. Lowercase class is a keyword in Java, and the capital of Class is class.

public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement {
}
复制代码

In the Java world, everything is an object, there are two objects in Java, a new object is to produce another Class object. Objects in general, we may be generated by the new keyword, the Class object can not, because it is used to generate a JVM class corresponding to the stored information. In other words, such as: When we define a class Person, compiled successfully, it will generate a Person.class byte code, this time from the compiler at the same time we create a Class object and save it in Person. class file. In other words: Person.java compiled into Person.class will produce a corresponding Class object.

Class object gets

In general, a Class object instance of the object corresponding to the following three ways to obtain:

1, by the method of Example getClass variables:

Person person = new Person();
Class personClass = person.getClass();
System.out.println("class1: " + personClass);
复制代码

2, given directly .class file object classes:

Class personClass1=Person.class;
System.out.println("class2: " + personClass1);
复制代码

If the object can not be created by the new keyword, we can also be obtained through a third way:

3, by the static method forName of class Class ():

try {
          Class personClass2 = Class.forName("reflect.Person");
          System.out.println("class3: " + personClass2);
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      }
复制代码

Print results are as follows:

class1: class reflect.Person
class2: class reflect.Person
class3: class reflect.Person
复制代码

Class use

JAVA reflection mechanism is in the operating state, for any class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; this information acquired dynamically and dynamic invocation a method of object function called reflection mechanism java language.

1, CLASS Gets the name for getting the name, Class class provides three methods:

Class.getName();
Class.getSimpleName();
Class.getCanonicalName();
复制代码

So what is the difference of these three ways? Further described by specific examples.

First we have to create a class Person.java

package reflect;
public class Person {
    private int age;
    private String name;
    public Person() {
    }
    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
复制代码

Then respectively acquire its Class name:

      //getName()方式
      Person person = new Person();
      Class personClass = person.getClass();
      System.out.println("class1: " + personClass.getName());
 //getSimpleName()方式
      Class personClass1=Person.class;
      System.out.println("class2: " + personClass1.getSimpleName());
//getCanonicalName()方式
      try {
          Class personClass2 = Class.forName("reflect.Person");
          System.out.println("class3: " + personClass2.getCanonicalName());
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      }
复制代码

Print results are as follows:

class1: reflect.Person
class2: Person
class3: reflect.Person
复制代码

We can see the first results obtained and the third way is the same, but only the second is not the same. And in thirteen get is the full path to the class, while the second is to get the class name, do not include the package name. The thirteen kinds What's the difference can be investigated by the internal class class.

2, modifiers get in Java modifiers are mainly private, public, static, protected, and so on. Java reflection API to provide access to these modifiers.

Modifiers to get through Class.getModifiers ()

Person person = new Person();
Class personClass = person.getClass();
System.out.println("modifiers: " + personClass.getModifiers());
复制代码

The results are as follows:

modifiers: 1
复制代码

The return type is an int value. Why will return an integer value it? This is because when a class definition may be more than one modifier modified, in order to get together, so Java engineers took into account the bit operation, with an int value to record all the modifiers, and different bit corresponding to different modifiers these modifiers are defined in the corresponding bit among the modifier class.

public class Modifier {
    public static final int PUBLIC           = 0x00000001;
    public static final int PRIVATE          = 0x00000002;
    public static final int PROTECTED        = 0x00000004;
    public static final int STATIC           = 0x00000008;
    public static final int FINAL            = 0x00000010;
	......
	public static String toString(int mod) {
        StringBuilder sb = new StringBuilder();
        int len;
        if ((mod & PUBLIC) != 0)        sb.append("public ");
        if ((mod & PROTECTED) != 0)     sb.append("protected ");
        if ((mod & PRIVATE) != 0)       sb.append("private ");
        /* Canonical order */
        if ((mod & ABSTRACT) != 0)      sb.append("abstract ");
        if ((mod & STATIC) != 0)        sb.append("static ");
        if ((mod & FINAL) != 0)         sb.append("final ");
        if ((mod & TRANSIENT) != 0)     sb.append("transient ");
        if ((mod & VOLATILE) != 0)      sb.append("volatile ");
        if ((mod & SYNCHRONIZED) != 0)  sb.append("synchronized ");
        if ((mod & NATIVE) != 0)        sb.append("native ");
        if ((mod & STRICT) != 0)        sb.append("strictfp ");
        if ((mod & INTERFACE) != 0)     sb.append("interface ");
        if ((len = sb.length()) > 0)    /* trim trailing space */
            return sb.toString().substring(0, len-1);
        return "";
    }
复制代码

Of course, if you want to print the string, it can be provided through the Modifier class static method toString to get.

System.out.println("modifiers: " + Modifier.toString(personClass.getModifiers()));
复制代码

3, Get CLASS members of a class member includes properties, methods, constructors. It is mapped to the Class Field, Method, Constructor. Next we come through concrete examples of how to get familiar with these members.

3.1 acquiring Field Gets attribute specifies the name of the API:

public Field getDeclaredField(String name)
                       throws NoSuchFieldException,
                              SecurityException;
public Field getField(String name)
               throws NoSuchFieldException,
                      SecurityException
复制代码

The difference is getDeclaredField () to obtain a modified Class are private property. getField () method to obtain non-private property, and getField () Class acquiring the ancestor will then get the current time is less than.

Get all the attributes.

//获取所有的属性,但不包括从父类继承下来的属性
public Field[] getDeclaredFields() throws SecurityException {}

//获取自身的所有的 public 属性,包括从父类继承下来的。
public Field[] getFields() throws SecurityException {}
复制代码

3.2 Get Method, Method, i.e., a method of Class.

public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
public Method getMethod(String name, Class<?>... parameterTypes)
public Method[] getDeclaredMethods() throws SecurityException
public Method getMethod(String name, Class<?>... parameterTypes)
复制代码

3.3, get Constructor

public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
public Constructor<T> getConstructor(Class<?>... parameterTypes)
public Constructor<?>[] getDeclaredConstructors() throws SecurityException 
public Constructor<?>[] getConstructors() throws SecurityException
复制代码

The use of reflection

Class above is acquired in a simple field method, constructor, these control mechanisms is reflected fields, methods, constructors.

About the Author

Focus on Android development for many years, likes to write blog records summarize learning experience, synchronized updates on my blog public number, welcome everyone's attention, can talk about ~

Here Insert Picture Description

Guess you like

Origin juejin.im/post/5dd3e1836fb9a01fdf7c08ee