In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what is the principle of Java reflection mechanism and how to obtain Class". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the principle of Java reflection mechanism and how to get Class".
1. What is the mechanism of Java reflection? 1.1 reflection principle
(1) Java reflection mechanism (Java Reflection) is a dynamic (runtime) ability to access, detect and modify itself in Java language. Its main function is to dynamically (runtime) obtain the complete structural information of the class & the method of calling the object.
To put it more simply, the Java program creates a reflection object of a class at run time (dynamically), and then performs related operations on the class, such as:
Get the member variable of the object & assignment
Call the method of the object (with constructor, with / without parameters)
Determine the class to which the object belongs
PS: but to be honest, it's a little difficult to understand the more official definition directly. Let's say it in a more common way.
(2) in general, when we use a class, we will know the class and what we want to do with it. We can create an object directly through new instantiation, and then use this object to operate on the class. This belongs to orthophoto.
(3) reflection does not know what class to initialize at first, so it is impossible to use new to instantiate and create an object, mainly through the reflection API provided by JDK. It is only at runtime that you know what class to operate, and you can get the complete construction of the class and call the corresponding method. This is reflection ~
1.2 reflection example
The code is as follows:
Package com.justin.java.lang;import java.lang.reflect.Constructor;import java.lang.reflect.Method;/** * @ program: Jdk1.8 Test * @ description: simple call example of orthophoto and reflection * @ author: JustinQin * @ create: 13:23 * @ version: v1.0.0 * * / public class Student {private int id; public void setId (int id) {this.id = id } public int getId () {return id;} public static void main (String [] args) throws Exception {/ / 1. Orthographic calling procedure Student student = new Student (); student.setId (1); System.out.println ("Orthographic calling procedure Student id:" + student.getId ()) / II. Reflection calling procedure Class clz = Class.forName ("com.justin.java.lang.Student"); Constructor studentConstructor = clz.getConstructor (); Object studentObj = studentConstructor.newInstance (); Method setIdMethod = clz.getMethod ("setId", int.class); setIdMethod.invoke (studentObj, 2); Method getIdMethod = clz.getMethod ("getId") System.out.println ("Orthographic calling procedure Student id:" + getIdMethod.invoke (studentObj));}}
Output result:
Orthographic calling procedure Student id:1 reflection calling procedure Student id:2
In the calling process of reflection in the above example, you can see that the reflection object of a class is obtained. The main process is:
Get the Class instance object of the class
Get Constructor object based on Class instance object
Then obtain the reflection object of the class according to the newInstance method of the Constructor object
After you get the reflection object of the class, you can operate on the class ~ for example, the procedure for calling the method of the class in the above example is:
Get the Method object of the class according to the Class instance object
Then call the method of the concrete class according to the invoke method of the Method object
The previous point also mentioned getting the Class instance object of the class. In the reverse call process of the above example, we obtain the Class instance object of the class through Class.forName ("global naming of the class"). In addition to this, there are two other commonly used methods, which are explained below.
2. Three ways of obtaining Class in Java reflection mechanism and their differences?
2.1 several ways to obtain Class
(1) the three common ways to obtain the java.lang.Class instance object of a class are:
Obtained through MyClass.class, where MyClass refers to the specific class ~ ~
Obtained by Class.forName ("global naming of the class"), the global name is package name + class name.
Obtained through new MyClass () .getClass (), where MyClass refers to the specific class ~
(2) through MyClass.class, JVM will load the class into memory using the ClassLoader class loader, but will not do any initialization of the class and return the java.lang.Class object.
(3) get it through Class.forName ("global naming of the class"). Similarly, the class will be loaded into memory by JVM, and the class will be statically initialized to return the java.lang.Class object.
(4) get it through new MyClass (). GetClass (), which uses new for instantiation, so both static and non-static initialization work will be carried out. The getClass method belongs to the method in the top-level Object class, and any subclass object can be called. Any subclass calls will return the java.lang.Class object of that subclass.
PS: in these three ways, the java.lang.Class object of the corresponding class in the JVM heap area eventually belongs to the same, that is, the memory address is the same. The result of the = = double equal sign comparison is true, because the same ClassLoader class loader is used to load a class in the JVM class loading process. No matter how many times it is loaded, there is always only one java.lang.Class object generated to the heap area, unless a custom class loader is used. Break JVM's parent delegation mechanism so that the same class is loaded by different class loaders before JVM treats it as two different java.lang.Class objects
2.2 Code demonstrates the differences between several ways
Create an entity class, and create static code block, dynamic code block, parameter construction method and no parameter construction method of the class in the entity class, which is convenient to test the difference between several methods and whether the memory address is the same.
(1) entity class:
Public class MyClass {private static final String staticStr= "Hi"; private static int staticInt= 2021; private String id; static {System.out.println ("static code block: staticStr=" + staticStr + ", staticInt=" + staticInt);} {System.out.println ("dynamic code block ~");} public MyClass () {System.out.println ("no parameter construction method ~") } public MyClass (String id) {System.out.println ("parametric construction method ~"); this.id = id;} public String getId () {return id;} public void setId (String id) {this.id = id } @ Override public String toString () {return "MyClass {" + "id='" + id +'\'+'}';}}
(2) Unit test class:
Unit test the three methods respectively through @ Test annotation, and then unit test the combination of the three methods ~
Package com.justin.java.lang;import org.junit.Test;/** * @ program: Jdk1.8Test * @ description: three common ways to obtain Class instance objects of a class in the Java reflection mechanism and their differences: * @ author: JustinQin * @ create: 2021-8-22 15:04 * @ version: v1.0.0 * * / public class MyClassTest {@ Test public void test1 () {System.out.println ("one, MyClass.class mode =") Class class1 = MyClass.class;} @ Test public void test2 () throws ClassNotFoundException {System.out.println ("II, Class.forName mode ="); Class class2 = Class.forName ("com.justin.java.lang.MyClass");} @ Test public void test3 () {System.out.println ("III, new MyClass (). GetClass mode ="); Class class3 = new MyClass (). GetClass () } @ Test public void test12 () throws ClassNotFoundException {System.out.println ("I, MyClass.class ="); Class class1 = MyClass.class; System.out.println ("II, Class.forName ="); Class class2 = Class.forName ("com.justin.java.lang.MyClass");} @ Test public void test13 () {System.out.println ("I, MyClass.class =") Class class1 = MyClass.class; System.out.println ("III, new MyClass (). GetClass mode ="); Class class3 = new MyClass () .getClass ();} @ Test public void test23 () throws ClassNotFoundException {System.out.println ("II, Class.forName mode ="); Class class2 = Class.forName ("com.justin.java.lang.MyClass") System.out.println ("III, new MyClass (). GetClass mode ="); Class class3 = new MyClass (). GetClass ();} @ Test public void test () throws ClassNotFoundException {System.out.println ("comparison of memory addresses in four or three modes ="); Class class1 = MyClass.class; Class class2 = Class.forName ("com.justin.java.lang.MyClass") Class class3 = new MyClass (). GetClass (); System.out.println ("comparison result ="); System.out.println ("whether MyClass.class and Class.forName memory address comparison is the same:" (class1 = = class2)); System.out.println ("MyClass.class and new MyClass () .getClass memory address comparison:" + (class1 = = class3)) System.out.println ("Class.forName and new MyClass (). GetClass memory address comparison is the same:" + (class2 = = class3));}}
Execute the unit one by one, and the test results are as follows:
* test1 () method 1, MyClass.class mode = * test2 () method 2, Class.forName mode = static code block: staticStr=Hi,staticInt=2021* test3 () method 3, new MyClass (). GetClass mode = static code block: staticStr=Hi,staticInt=2021 dynamic code block ~ no parameter construction method ~ * test12 () method 1, MyClass.class mode = 2, Class.forName mode = static code block: staticStr=Hi StaticInt=2021* test13 () method 1, MyClass.class mode = 3, new MyClass (). GetClass mode = static code block: staticStr=Hi,staticInt=2021 dynamic code block ~ no parameter construction method ~ * test23 () method 2. Class.forName mode = static code block: staticStr=Hi,staticInt=2021 3, new MyClass (). GetClass mode = dynamic code block ~ no parameter construction method ~ * test () method IV, memory address comparison of three modes = static code block: staticStr=Hi StaticInt=2021 dynamic code block ~ No parameter construction method ~ comparison result = whether MyClass.class and Class.forName memory address comparison is the same: trueMyClass.class and new MyClass (). GetClass memory address comparison is the same: trueClass.forName and new MyClass (). GetClass memory address comparison is the same: true
Through the test results of test1, test2 and test3, this paper verifies the differences of the yellow marks in the three ways and differences, namely:
MyClass.class will not do any class initialization work
Class.forName does the static initialization of the class
New MyClass (). GetClass static initialization and non-static initialization work will be carried out
Using any of these three methods will end up with the same memory address when the JVM is loaded into memory.
The test results obtained by test23 combination show that static code blocks will only be loaded once.
Having said so much, in addition to knowing the basic principles and basic use, it is more important to know some of its more practical application scenarios.
3. What are the application scenarios of Java reflection mechanism?
3.1 Application scenario
Simple Factory pattern Optimization in Factory Model
Implementation of dynamic Agent in Agent Mode
Java JDBC database operation
3.2 simple factory model optimization 3.2.1 what is a simple factory model?
There are mainly 23 design patterns in Java, and the factory pattern is one of them, and the simple factory pattern, as its name implies, is also one of the factory patterns, but it is relatively simple. A simple factory pattern can also be called a static method pattern (because factory classes generally define a static method internally).
From the perspective of real life, the factory is responsible for the production of products, also in the design pattern, the simple factory pattern can be understood as a class specifically responsible for the production of objects, called the "factory class".
3.2.2 what is the use of a simple factory model?
By creating a corresponding factory class, the simple factory pattern separates the instantiation of the class from the operation of the object, so that the user can instantiate the specific product class without knowing the specific parameters. as a result, it avoids being explicitly specified in the client code and realizes decoupling. Even if the user can consume the product directly without knowing the details of its production.
3.2.3 how to implement a simple engineering model?
The core of implementing the simple engineering pattern is to create a factory class, and define a static method internally, pass in different parameter identifiers and group them by switch, and instantiate through new to create different subclass objects to return ~
Implementation example:
Step 1: create an abstract product class
Public interface Product {public abstract void show ();}
Step 2: create a specific product category:
Public class ProductA implements Product {@ Override public void show () {System.out.println ("Product A");} public class ProductB implements Product {@ Override public void show () {System.out.println ("Product B");}} public class ProductC implements Product {@ Override public void show () {System.out.println ("Product C");}}
Step 3: create a simple factory class
Public class SimpleFactory {/ * implement simple factory pattern * @ param pName product ID * @ return returns specific product * / public static Product createProduct (String pName) {switch (pName) {case "A": return new ProductA (); case "B": return new ProductB () Case "C": return new ProductC (); default: return null;}}
Step 4: call the simple factory class
Public class SimpleFactoryTest {public static void main (String [] args) {try {SimpleFactory.createProduct ("A"). Show ();} catch (NullPointerException e) {System.out.println ("cannot be produced without A);} try {SimpleFactory.createProduct (" B ") .show () } catch (NullPointerException e) {System.out.println ("cannot be produced without B);} try {SimpleFactory.createProduct (" C "). Show ();} catch (NullPointerException e) {System.out.println (" cannot be produced without C ") } try {SimpleFactory.createProduct ("D"). Show ();} catch (NullPointerException e) {System.out.println ("cannot be produced without D);}} 3.2.4 simple factory model optimization
(1) disadvantages of simple factory model
High operating cost: each additional subclass of an interface must modify the logic of the factory class
Increased system complexity: with each additional subclass of an interface, logic must be added to the factory class
These two drawbacks from the previous example of the implementation of the SimpleFactory factory class, we can see that the maintenance cost of the factory class SimpleFactory in the simple factory pattern is a bit high, because in practice, the specific product class may be updated very frequently, and each change needs to modify the factory class. At this time, we can use the Java reflection mechanism to optimize the simple factory pattern.
(2) the optimization idea of simple factory model.
Using the Java reflection mechanism, different subclass object instances are dynamically created by passing in the global subclass name (package name + class name), so that the factory class can uniformly create the subclass instance object without adding the product interface subclass and modifying the logic of the factory class.
(3) the optimization steps of simple factory model.
Step 1: create a factory class
The factory class is optimized by Java reflection mechanism, which mainly takes className, that is, the global name of the subclass (package name + class name) as the input parameter, obtains the java.lang.Class instance object of the class by Class.forName, and then obtains the instance object of the concrete subclass through the getInstance method of the Class instance object.
Public class Factory {public static Product getInstance (String className) {Product realProduct = null; try {Class pClass = Class.forName (className); realProduct = (Product) pClass.newInstance ();} catch (Exception e) {e.printStackTrace ();} return realProduct;}}
Step 2: invoke the factory class
Public class FactoryTest {public static void main (String [] args) {try {Product productA = Factory.getInstance ("com.justin.java.lang.ProductA"); productA.show ();} catch (NullPointerException e) {System.out.println ("cannot be produced without A ~") } try {Product productB = Factory.getInstance ("com.justin.java.lang.ProductB"); productB.show ();} catch (NullPointerException e) {System.out.println ("cannot be produced without B");} try {Product productC = Factory.getInstance ("com.justin.java.lang.ProductC") ProductC.show ();} catch (NullPointerException e) {System.out.println ("cannot be produced without C");} try {Product productD = Factory.getInstance ("com.justin.java.lang.ProductD"); productD.show () } catch (Exception e) {System.out.println ("cannot be produced without D);}"
Optimization results:
After optimizing the simple factory pattern by using the Java reflection mechanism, we can see that no matter how frequently the specific product class is updated, there is no need to modify the factory class, thus solving the problems of high operating cost and high system complexity of the ordinary simple factory mode.
3.2.5 simple factory model is optimized again
(1) optimize the background again
After the factory class of simple factory pattern is optimized by Java reflection mechanism, there is still a problem that the global naming of subclasses (package name + class name) is written dead, but in fact, it is very difficult for developers to predict the global naming of all subclasses (package name + class name) in advance when writing code, so secondary optimization is needed.
(2) optimize the realization idea again.
Through the configuration file, uniformly define the class name corresponding to the global name (package name + class name), store the configuration file in the resource directory, and dynamically obtain the global name of the subclass defined in the configuration file through the ClassLoader class loader when the program is running.
(3) optimize the implementation steps again.
Step 1: the relevant optimization remains the same as the first optimization.
Optimize step 2 again: configure the class name corresponding to the global name (package name + class name)
Create a property profile Product.properties
/ / Global naming (package name + class name) definition of Product related subclasses of product abstract class ProductA = com.justin.java.lang.ProductAProductB = com.justin.java.lang.ProductBProductC = com.justin.java.lang.ProductC
Note: Product.properties needs to be stored in the src/main/resources resource directory. If the resource directory does not exist, it needs to be created manually ~
Optimize step 3 again: modify the calling factory class
Public class FactoryTest {@ Test public void test () throws IOException {ClassLoader classLoader = this.getClass () .getClassLoader (); Properties prop = new Properties (); prop.load (classLoader.getResourceAsStream ("Product.properties")); String className = ""; try {className = prop.getProperty ("ProductA"); Product productA = Factory.getInstance (className); productA.show () } catch (NullPointerException e) {System.out.println ("cannot be produced without A");} try {className = prop.getProperty ("ProductB"); Product productA = Factory.getInstance (className); productA.show () } catch (NullPointerException e) {System.out.println ("cannot be produced without B");} try {className = prop.getProperty ("ProductC"); Product productA = Factory.getInstance (className); productA.show () } catch (NullPointerException e) {System.out.println ("cannot be produced without C);}"
Running result:
Production of product A, production of product B, production of dynamic agent implementation in product C3.3 agent mode
3.3.1 what is the agency mode?
Proxy pattern is a design pattern, which accesses the target object through the proxy object, and extends the proxy object without modifying the target object to enhance the function of the target object.
What? Still don't understand?
In a more popular way, the agency model is that you want to do something (buy a train ticket), you can buy it by yourself (go directly to the railway station), but entrust someone else to buy it (if you don't have time, buy it by an agent). You can also ask others to do other things for yourself (book a hotel) ~
The agent mode is divided into static agent and dynamic agent.
3.3.2 what is a static agent?
(1) static proxy belongs to the proxy mode, which requires the proxy object and the target object to implement the same interface.
(2) the source code of the static proxy class is written by the programmer, and the class bytecode file of the proxy class can be obtained after compilation, that is, the actual class bytecode file of the proxy class is obtained before the program runs.
3.3.2 what is a dynamic agent?
Dynamic agent
(1) dynamic proxy is also a proxy mode of proxy mode, but only the target object implements the interface, and the proxy object does not need to implement the interface.
(2) the agent class of the dynamic proxy does not have the class bytecode file after compilation, but dynamically generates the class bytecode file of the proxy class by using the Java reflection mechanism at run time.
The most commonly used dynamic agents are JDK native dynamic agent and cglib dynamic agent.
JDK native dynamic agent
JDK native dynamic agent, mainly using JDK API's
Java.lang.reflect.Proxy and java.lang.relfect.InnvocationHandler are two classes to implement ~
Through the newProxyInstance method of the java.lang.reflect.Proxy proxy class, pass three parameters, which are:
The loader of the target object is obtained by MyClass.getClass (). GetClassLoader
The implementation interface type of the target object is obtained by Object.getClass (). GetInterfaces ()
The InnvocationHandler event handler gets the new by instantiating the object and overriding the invoke method
Example:
User interface class IUserDao
Public interface IUserDao {/ / add data public void insert ();}
Target object class UserDao
/ * @ program: DataStructures * @ description: * @ author: JustinQin * @ create: 23:32 * @ version: v1.0.0 * * / public class UserDao implements IUserDao {@ Override public void insert () {System.out.println ("add data");}}
Dynamic proxy class UserProxy
/ * @ program: Jdk1.8Test * @ description: dynamic proxy class * @ author: JustinQin * @ create: 2021-8-23 23:31 * @ version: v1.0.0 * * / public class UserProxy {private Object target; / / Target object public UserProxy (Object target) {this.target = target } / * obtain the loader ClassLoader loader = target.getClass () .getClassLoader () of the proxy object * @ return * / public Object getProxyInstance () {/ / target object using JDK API; / / the implementation interface type of the target object Class [] interfaces = target.getClass () .getInterfaces () / / InnvocationHandler event handler instance object InvocationHandler h = new InvocationHandler () {@ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System.out.println ("before adding data: manually opening a transaction"); / / execute the target object method Object value = method.invoke (target, args) System.out.println ("after adding data: manually commit transaction"); return null;}}; / / pass in three parameters, create an instance object of the proxy class, and return return Proxy.newProxyInstance (loader, interfaces,h);}}
Dynamic proxy unit test class
/ * * @ program: dynamic agent unit test class * @ description: * @ author: JustinQin * @ create: 2021-8-23 23:42 * @ version: v1.0.0 * * / public class UserProxyTest {@ Test public void test () {IUserDao target = new UserDao (); System.out.println ("Target object Information:" + target.getClass ()) / / get proxy class instance object IUserDao proxy = (IUserDao) new UserProxy (target). GetProxyInstance (); System.out.println ("proxy object Information:" + proxy.getClass ()); / / execute proxy method proxy.insert ();}}
Unit test execution results
Target object information: class com.justin.java.reflect.UserDao proxy object information: before class com.sun.proxy.$Proxy2 add data: manually open transaction add data after adding data: submit transaction manually
Cglib dynamic agent
Cglib (Code Generation Library) is a third-party code generation class library, which dynamically generates a subclass object in memory at run time to extend the function of the target object.
Spring AOP combines cglib dynamic agent and JDK native dynamic agent to implement. Here is not too much introduction. If you are interested, you can consult the materials and learn.
3.3.3 how can the Java reflection mechanism be used in dynamic agents?
In the JDK native dynamic proxy, in the process of obtaining the proxy sample object, the class loader of the target object is obtained, and the Class instance object of the target object is obtained by target.getClass (). GetClassLoader (get the classloader of the target object, and the Class instance object of the target object is obtained by using the Java reflection mechanism).
3.4 implementation of Java JDBC database operation 3.4.1 loading JDBC driver using reflection
I believe many partners know that Java JDBC connection to the database is mainly divided into seven steps, of which the first step is to load the JDBC driver and use the Java reflection mechanism to load the drivers of different databases by passing in different driver names.
Class.forName ("com.mysql.jdbc.Driver"); / / load MySQL driver Class.forName ("oracle.jdbc.driver.OracleDriver"); / / load Oracle driver 3.4.2 Java JDBC connection example
Create test library tables and data
Create DATABASE test;-- DROP TABLE IF EXISTS test.user;create table test.user (id int (7) primary key not null auto_increment,name varchar, sex char (1), age int (3)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;insert into TEST.user (name,sex,age) values ('Zhang Yi', 'male', 21); insert into TEST.user (name,sex,age) values ('Zhang er', 'female', 22) Insert into TEST.user (name,sex,age) values ('Zhang San', 'male', 23)
Seven steps of Java MySQL JDBC connection ~
Public static void main (String [] args) throws ClassNotFoundException, SQLException {/ / 1. Load the JDBC driver Class.forName ("com.mysql.jdbc.Driver"); / / 2. Get the database Connection object Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test", / / mysql connection url,test indicates the database name you want to connect to "root", / / database user name "abc@123456"); / / password / / 3. Get database operation (PrepareStatement) object PreparedStatement prepareStatement = connection.prepareStatement ("select * from TEST.user where id =?"); / / 4. Set the input parameters prepareStatement.setInt (1,1); / / 5. Upload the sql statement to the server to execute (excute) and return the result set (ResultSet) ResultSet result = prepareStatement.executeQuery (); / / 6. Processing the returned ResultSet result set while (result.next ()) {System.out.print (result.getInt ("id") + ","); System.out.print (result.getString ("name") + ","); System.out.print (result.getString ("sex") + ","); System.out.print (result.getInt ("age")) System.out.print ("\ n");} / / 7. Release related resources: Connection object, PrepareStatement object, ResultSet object. Connection.close (); prepareStatement.close (); result.close ();}
Execution result:
1, Zhang Yi, male, 21
Seven steps of Java Oracle JDBC connection ~
Public class JdbcOracleTest {public static void main (String [] args) throws ClassNotFoundException, SQLException {/ / 1. Load the JDBC driver Class.forName ("oracle.jdbc.driver.OracleDriver"); / / 2. Get database connection (Connection) object Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@127.0.0.1:1521:orcl", / / oracle connection url "root", / / database user name "abc@123456"); / / password / / 3. Get database operation (PrepareStatement) object PreparedStatement prepareStatement = connection.prepareStatement ("select * from TEST.user where id =?"); / / 4. Set the input parameters prepareStatement.setInt (1,1); / / 5. Upload the sql statement to the server to execute (excute) and return the result set (ResultSet) ResultSet result = prepareStatement.executeQuery (); / / 6. Processing the returned ResultSet result set while (result.next ()) {System.out.print (result.getInt ("id") + ","); System.out.print (result.getString ("name") + ","); System.out.print (result.getString ("sex") + ","); System.out.print (result.getInt ("age")) System.out.print ("\ n");} / / 7. Release related resources: Connection object, PrepareStatement object, ResultSet object. Connection.close (); prepareStatement.close (); result.close ();}}
PS: above, connect to the database and operate through Java JDBC. The connection here is a single connection, which is established directly through DriverManager.getConnection, the native database connection of Java. Now in actual Java Spring projects, it is achieved by configuring the database connection pool of mybatis, but the principle is the same. The loading driver also uses the Java reflection mechanism to specify different driver names. Implement loading of different database drivers
Database connection pool configuration spring-mybatis.xml
Database configuration Information jdbc.propertis
# Database connection driver app-data-source.driverClassName=com.mysql.jdbc.Driver# database connection urlapp-data-source.url=jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=UTF-8# database user app-data-source.username=root# database user password (encrypted) app-data-source.password=abc@123456# connection pool initialization size app-data-source.initialSize=10# connection pool maximum number of app-data-source.maxActive=50# connection pool Large idle app-data-source.maxIdle=20# connection pool minimum idle app-data-source.minIdle=5# get connection maximum wait time app-data-source.maxWait=30000 interview summary
1. What is the mechanism of Java reflection?
1. Java reflection mechanism (Java Reflection) is a dynamic (runtime) ability to access, detect and modify itself in Java language. its main function is to dynamically (runtime) obtain the complete structural information of the class & the method of calling the object.
To put it more simply, the Java program creates a reflection object of a class at run time (dynamically), and then performs related operations on the class, such as:
Get the member variable of the object & assignment
Call the method of the object (with constructor, with / without parameters)
Determine the class to which the object belongs
2. More generally, when we use a class, we all know the class and what we want to do with it. We can create an object directly through new instantiation, and then use this object to operate on the class. This belongs to orthophoto.
3. Reflection does not know what class to initialize at first, so it is impossible to use new to instantiate and create an object, mainly through the reflection API provided by JDK. It is only at runtime that you know what class to operate, and you can get the complete construction of the class and call the corresponding method. This is reflection ~
2. Three ways of obtaining Class in Java reflection mechanism and their differences?
1. The three common ways to obtain the java.lang.Class instance object of a class are:
Get it through MyClass.class
Get through Class.forName ("global naming of the class")
Get it through new MyClass (). GetClass ()
2. Through MyClass.class, JVM will use the ClassLoader class loader to load the class into memory, but will not do any initialization of the class and return the java.lang.Class object
3. Get it through Class.forName ("Global naming of the class"). Similarly, the class will be loaded into memory by JVM, and the class will be statically initialized to return the java.lang.Class object.
4. Get it through new MyClass (). GetClass (), which uses new for instantiation, so both static initialization and non-static initialization work will be carried out. The getClass method belongs to the method in the top-level Object class and can be called by any subclass object. Any subclass call returns the java.lang.Class object of that subclass.
5. In these three ways, in the end, the java.lang.Class object of the corresponding class in the JVM heap area belongs to the same, that is, the memory address is the same. The result of the = = double equal sign comparison is true, because the JVM class loader uses the same ClassLoader class loader to load a class, no matter how many times it is loaded, there is always only one java.lang.Class object generated to the heap area, unless the custom class loader destroys the parent delegation mechanism of JVM. So that the same class is loaded by different class loaders, JVM will treat it as two different java.lang.Class objects
3. What are the application scenarios of Java reflection mechanism?
Simple Factory pattern Optimization in Factory Model
Implementation of dynamic Agent in Agent Mode
Java JDBC database operation
Thank you for reading, the above is the content of "what is the principle of Java reflection mechanism and how to obtain Class". After the study of this article, I believe you have a deeper understanding of the principle of Java reflection mechanism and what is the way to get Class. The specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.