This is the complete collection of Java zero basics and java reflection mechanism recommended by architects in front-line factories. You only need to read this article

Use of reflection 1: reflection of Constructor

Again, we can construct a new Student through a public null parameter, but we cannot construct a new private full parameter.

Student student = new Student();

Now let's construct the reflection constructor (create an instance in the form of reflection)

public static void main(String[] args)

           throws NoSuchMethodException, IllegalAccessException,

           InvocationTargetException, InstantiationException {

       //Get Class object

       Class<?> clazz = Student.class;

       /*

           Get the corresponding constructor according to the parameter type

           The parameter type is a formal parameter type

        */

       Constructor<?> constructor = clazz.getConstructor();

       /*

           Create instance

           The parameter type is an argument type (formal parameters correspond to each other one by one)

        */

       Object obj = constructor.newInstance();

       System.out.println("obj = " + obj);

}

The Student object obtained in this way has the same effect as the object obtained from the new null parameter constructor (it is meaningless in actual business development).

The former creates objects by new, which is more passive than objects created by reflection. The former is created by new, while the former creates itself (objects) by reflection, and the construction method is mainly objective.

Another way is to create constructors directly from Class objects:

public static void main(String[] args)

           throws  IllegalAccessException, InstantiationException {

       //Get Class object

       Class<?> clazz = Student.class;

       /*

           Create an instance by calling the null parameter construct by default

           jdk9 Out of date in

       */

       Object obj = clazz.newInstance();

       System.out.println("obj = " + obj);

   }

In the Student class, there is also a private constructor. Normally, objects cannot be created through private constructors., But reflection can:

public static void main(String[] args)

           throws NoSuchMethodException, IllegalAccessException,

           InvocationTargetException, InstantiationException {

       //Get Class object

       Class<?> clazz = Student.class;

       /*

           Get construct

           Because the permission is private, getConstructor() can only get methods decorated with public

           getDeclaredConstructor():Gets the declared method. As long as it is declared

        */

      Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, int.class);

      System.out.println("Full parameter private structure:" + constructor);

       /*

           Private structure, newInstance will generate illegal access exception: Java lang.IllegalAccessException

           So change the permission setaccessible() -- >

        */

       constructor.setAccessible(true);

      Object obj = constructor.newInstance("Xiao Ming",20);



       System.out.println("obj = " + obj);

   }

The above is to use reflection to create an object (reflection constructor).

Use of reflection 2: reflection of Method

Next, look at the reflection of the two methods in the Student object

We used (external) methods to call (non private) methods through objects. If it is a static method, it is called directly by classes.

So, what do you do when you use reflection to call (non private) methods?

public static void main(String[] args)

           throws NoSuchMethodException, IllegalAccessException,

           InvocationTargetException {

       //Get Class object

       Student student = new Student();

       Class<? extends Student> clazz = student.getClass();

       /*

           getMethod():Gets the method in the Class object

           Parameter 1: method name

           Parameter 2: parameter list type

        */

       Method show = clazz.getMethod("show", String.class);

       /*

           Calling the show method requires objects and parameters

           invoke()Method: call meaning

           Parameter 1: the object that calls this method

           Parameter 2: the passed in arguments are required to call this method

        */

       show.invoke(student, "hello public show");

   }

Reflection can be understood as inversion in language grammar:

When we write code, I (object) call the method. Here is:

new Student().show("object calls method");

And on show invoke(student, “hello public show”); In,

The show method considers who will call me, and then the student object says, I'll call you (student as a parameter).

Extension: if the static keyword is added to the public show method, will it affect the method call?

Tip: static has nothing to do with objects

A: with the static keyword, ordinary code can be called even without the new object. As we all know, in show invoke(Student, “hello public show”); Writing null to parameter 1 in the does not affect it, because the show method comes from the Student's Class object.

Next, let's look at how reflection of private methods is implemented?

ps: the API s of reflection channels are very regular and readable

public static void main(String[] args)

           throws NoSuchMethodException, IllegalAccessException,

           InvocationTargetException {

        //Get Class object

       Student student = new Student();

       Class<? extends Student> clazz = student.getClass();

       /*

           getDeclaredMethod():Get the declared methods in the Class object (including)

           Parameter 1: method name

           Parameter 2: parameter list type

        */

       Method speak = clazz.getDeclaredMethod("speak", String.class, int.class);

       //Private method, violent reflection

       speak.setAccessible(true);

       /*

           Calling the show method requires objects and parameters

           invoke()Method: call meaning

           Parameter 1: the object that calls this method

           Parameter 2: the passed in arguments are required to call this method

        */

       speak.invoke(student, "hello private speak",2018);

   }

Use of reflection 3: reflection of attribute (Field)

There is a common attribute and a private attribute in the Student entity. We can set the value of the common attribute through the object. How to assign the value of all attributes through reflection?

Let's first look at the assignment of the common attribute name

public static void main(String[] args)

           throws ClassNotFoundException, NoSuchFieldException,

           IllegalAccessException, InstantiationException {

        //Get the Class object, parameter fully qualified name

       Class<?> clazz = Class.forName("com.test.demo.Student");

       /*

           getField():Get property by property name

        */

       Field name = clazz.getField("name");

       //Get object

       Object obj = clazz.newInstance();

       /*

           Set a value

           Parameter 1: which object's attribute value

           Parameter 2: parameter

        */

       name.set(obj,"Zhang San");

       System.out.println(obj);

   }

last

Authoritative guide - the first Docker book

Lead the installation, deployment, management and expansion of Docker, let it go through the whole development life cycle from test to production, and deeply understand what scenarios Docker is suitable for. In addition, this authoritative guide to Docker introduces the basic knowledge of its components, and then uses Docker to build containers and services to complete various tasks: use Docker to establish a test environment for new projects, demonstrate how to integrate Docker using continuously integrated workflow, how to build application services and platforms, how to use Docker's API, and how to extend Docker.

It includes nine chapters: introduction, installing Docker, getting started with Docker, using Docker image and warehouse, using Docker in testing, using Docker to build services, using Fig to configure Docker, using Docker API, getting help and improving Docker.

The "K8S+Docker learning guide" strongly recommended by Ali - Kubernetes in simple terms: Theory + practice and authoritative guide - the first Docker book are described in two words after reading. I love it!

If you love too, Click here to download the "K8S+Docker" learning guide for free

Knowledge of Docker, using Docker API, getting help and improving Docker.

[external chain picture transferring... (img-qglPGbCX-1628310011826)]

[external chain picture transferring... (IMG oltgxazx-1628310011827)]

[external chain picture transferring... (img-ZL5tDXN5-1628310011828)]

[external chain picture transferring... (img-0A8OQTOZ-1628310011830)]

The "K8S+Docker learning guide" strongly recommended by Ali - Kubernetes in simple terms: Theory + practice and authoritative guide - the first Docker book are described in two words after reading. I love it!

If you love too, Click here to download the "K8S+Docker" learning guide for free

Keywords: Java Back-end Interview Programmer

Added by barrow on Sat, 01 Jan 2022 23:42:43 +0200