Reflection mechanism of java

I What is reflection

 Reflection is a dynamic mechanism in java, which allows us to determine the instantiation of objects and the call of methods during the running of programs,
 Property operation, etc. The flexibility of the program is greatly improved, but it also brings more resource overhead and lower cost
 Operation efficiency.
 Programs cannot rely too much on reflection mechanisms.

2. Reflection acquisition method

Class object
 Each instance of Class is used to represent a Class loaded in the JVM, and each Class loaded by the JVM is
 There is only one instance of Class.
Through Class, we can know all the information of the Class it represents: Class name, package name, constructors and methods
 Properties, etc. And perform relevant operations after obtaining during operation.

Therefore, the first step of reflection operation is to obtain the class object of the class to be operated.
The methods to obtain the class object of a class are:

1: Class name class
  For example:
  Class cls = String.class;
  Class cls = int.class;
Note: basic types can only obtain class objects in the above way
2: Class.forName(String className)
  Use the static method forName of class to pass in the fully qualified name (package name. Class name) of the class to be loaded
  For example:
  Class cls = Class.forName("java.lang.String")
3: ClassLoader form

3. Common methods

 Class cls = Class.forName("reflect.Person");

 //Get the relevant information of the String represented by the class object
        String name = cls.getName();  //Get package name and class name
        name = cls.getSimpleName();  //Get class name

        System.out.println(cls.getPackage().getName());  //Get package name

 //The class object provides a method newInstance() that can call the parameterized and exposed constructor instantiation
        Object o = cls.newInstance();

 2 Get the corresponding constructor  Person(String name,int age)
//        cls.getConstructor();// A parameter free constructor is obtained without passing parameters

//3 instantiate the object new Person("Wang Wu", 22) through the constructor;
        Object o = cls.newInstance("Wang Wu",22);

 //Gets all exposed methods of the class represented by the current class object (including methods inherited from the superclass)
        Method[] methods = cls.getMethods();

 //Get private method
        Method method = cls.getDeclaredMethod("secret");

 //Force open access

Invoke method using reflection mechanism: invoke

1. Call parameterless method

public class ReflectDemo4 {
    public static void main(String[] args) throws Exception {
        Person p = new Person();

        Scanner scanner = new Scanner(;
        System.out.println("Please enter the class name:");
        String className = scanner.nextLine();
        System.out.println("Please enter method name:");
        String methodName = scanner.nextLine();
//        Class cls = Class.forName("reflect.Person");
        Class cls = Class.forName(className);
        Object o = cls.newInstance();//Person o = new Person();
        //Gets the method to call
        //When only the method name is passed in, the parameterless method is obtained
//        Method method = cls.getMethod("sayHello");// Represents the member method sayHello() of the Person
        Method method = cls.getMethod(methodName);


2. Call the method with parameters

public class ReflectDemo5 {
    public static void main(String[] args) throws Exception {
        Class cls = Class.forName("reflect.Person");
        Object o = cls.newInstance();

        Method method = cls.getMethod("dosome",String.class);//dosome(String)
        method.invoke(o,"play a game");//p.dosome("play a game");

        Method method1 = cls.getMethod("dosome",String.class,int.class);
        method1.invoke(o,"Watch tv",5);

4. Annotations used in reflection


Define @ AutoRunClass annotation

This annotation is used to label classes that can be automatically called by the reflection mechanism

public @interface AutoRunClass {

 When defining annotations, we usually use two built-in annotations in java to modify them

1.@Retention is used to specify the retention level of the current annotation. There are three optional values,
  RetentionPolicy.SOURCE indicates that the current annotation is only kept in the source code
  RetentionPolicy. Class (default) means that annotations will remain in bytecode, but the reflection mechanism is not available
  RetentionPolicy. The runtime representation remains in the bytecode file, but can be used by the reflection mechanism
  Usually, the annotations we define will be specified as RUNTIME level to assist the operation of reflection mechanism.
2.@Target is used to indicate where the current annotation can be used. All options are defined on ElementType
 Common are:
   ElementType.TYPE is used on a class
   ElementType.FIELD is used in attributes
   ElementType.METHOD is used in the method

Judge whether it is annotated: isannotationpresent (annotation name. class)

public class ReflectDemo7 {
    public static void main(String[] args) throws Exception {
        //Judge whether a class is marked by @ AutoRunClass
//        Class cls = Class.forName("reflect.Person");
//        Class cls = Class.forName("reflect.Student");
        Class cls = Class.forName("reflect.Test2");
            In addition to Class, other reflection objects such as Method and file also support isAnnotationPresent
            Method to indicate whether the annotation is specified.
            For example:
            Method This method is to judge whether the method it represents is annotated.
            Constructor This method is to determine whether the constructor it represents is annotated.
            System.out.println(cls.getName()+":cover@AutoRunClass Marked!");
            System.out.println(cls.getName()+":Not by@AutoRunClass Marked!");


Keywords: Java Back-end

Added by drummer101 on Sat, 26 Feb 2022 05:02:44 +0200