Class object and reflection mechanism.
After understanding the concept of reflection mechanism, it can be seen that if you want to use java reflection mechanism to do something, you need to use Class object, so Class object is the premise of reflection.
So, how to get the Class object?
There are three ways to obtain Class objects in java:
-
Class name class
-
Object name gerClass
-
Class.forName("fully qualified name (package name + class name)");
Supplement: there are two types of Class objects
1. Normal Class object: Based on reference type
2. Predefined Class objects (in jvm): Based on basic type and void
Several functions of reflection mechanism:
-
Determine the class of any object at run time
-
Construct an object of any class at run time
-
Judge the member variables and methods of any class at run time
-
Call the method of any object at run time
Prepare a class first:
package com.test.demo; public class Student { public String name; private int age; public Student() { } private Student(String name, int age) { this.name = name; this.age = age; } public void show(String msg){ System.out.println("show method = " + msg); } private void speak(String msg,int number){ System.out.println("speak method = " + msg +":"+ number ); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
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");
last
There are also ways to brush questions for the interview. It is suggested that it is best to carry out according to the topic, and then from basic to advanced, from shallow to deep, the effect will be better. Of course, these contents are also sorted out in a pdf document and divided into the following topics:
- Java Basics
- Algorithm and programming
- Database part
- Popular frameworks and new technologies (Spring + spring cloud + spring cloud Alibaba)
Of course, there are more than these contents in this interview document. In fact, the interview contents of other parts such as JVM, design pattern, ZK, MQ and data structure are involved. Because of the length of the article, it is not all described here.
As a programmer, phased learning is essential and needs to maintain a certain continuity. This time, I systematically reviewed some key knowledge points at this stage, which not only consolidated my foundation, but also improved the breadth and depth of my knowledge.
Finally, let me remind you that if you want to learn, but you have no dry learning materials, all the above materials can be shared with you free of charge, as long as you give more support
)]
- Database part
[external chain picture transferring... (img-A50ml0dB-1628488641212)]
- Popular frameworks and new technologies (Spring + spring cloud + spring cloud Alibaba)
[external chain picture transferring... (img-PERosiOE-1628488641213)]
Of course, there are more than these contents in this interview document. In fact, the interview contents of other parts such as JVM, design pattern, ZK, MQ and data structure are involved. Because of the length of the article, it is not all described here.
As a programmer, phased learning is essential and needs to maintain a certain continuity. This time, I systematically reviewed some key knowledge points at this stage, which not only consolidated my foundation, but also improved the breadth and depth of my knowledge.
Finally, let me remind you that if you want to learn, but you have no dry learning materials, all the above materials can be shared with you free of charge, as long as you give more support
"Like articles, follow me, and then click here for free download"