Interview Questions of Big Factory Based on Java Reflection Mechanism

Interview Questions of Big Factory Based on Java Reflection Mechanism

Reflection mechanism concept

When the program is running, the Java reflection mechanism can know all the properties and methods of this class for any class; for any object, it can call any of its methods and properties. This dynamic access to information and a method for dynamic call object functions called java reflection mechanism .

Why introduce the concept of reflection

Believe that you see the concept above, there is no wave in your mind, dynamic information acquisition , dynamic call object method black question mark. The following simple code serves as the starting point for i and is explained from the perspective of the java virtual machine

  • Write the following code
public class Main{
    public static int number = 1;
    public static void main(String args[]) {
    	System.out.println("hello World");
    }
}
  • Call the javac Main.javacommand to Main.javacompile the Main.classfile into a file
  • After executing the java Maincommand, the java virtual machine is started, the class loading process is performed , the static storage structure of the class is stored in the method area , and a java.lang.Class object representing the class is generated in memory as each of the class in the method area Data access

The above process shows that during the compilation phase, the class (Main class) to be loaded by the Java virtual machine is already specified . If your program is running, you suddenly need to load the class of the remote server (loading during operation). At this time, the reflection mechanism comes into play.

There is a very classic scenario is to load the database driver class, only through the parameters at run time can you determine whether to load com.java.dbtest.myqlConnection(mysql driver class), or loadcom.java.dbtest.oracleConnection

At this point, only a simple call Class.forName(com.java.dbtest.myqlConnection)can dynamically complete the process of loading the class.

Use the reflection mechanism to load the class twice

import java.io.IOException;
import java.io.InputStream;
public class Main{
    public static void main(String args[]) throws Exception{
        //自定义类加载器
        ClassLoader myLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException{
                try{
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if(is == null) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0,  b.length);
                }catch(IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };
        //使用反射机制加载并实例化
        Object obj = myLoader.loadClass("Main").newInstance();

        System.out.print(obj instanceof Main);

    }
}

//结果为false

Since the initial stage is passed 双亲委派模型, the system application class loader has already loaded the class. At the runtime stage, a custom class loader is used. Based on the reflection mechanism, the class is loaded again. Two different class loaders are loaded again. , So the final result of the program is false.

Published 193 original articles · Liked 403 · Visits 150,000+

Guess you like

Origin blog.csdn.net/zycxnanwang/article/details/105525658