Dynamic loading is not suitable for array classes? How to dynamically load an array class?

Absrtact: since the array is a class, what is the compiled class name? What about the classpath? Why is dynamic loading not suitable for arrays? How to dynamically load an array?

This article is shared from Huawei cloud community< [JAVA cold knowledge] dynamic loading is not suitable for array classes? How to dynamically load an array class? >, author: the mountains and rivers are all right.

  • Today, I'd like to share some java tips with my friends, mainly focusing on the following points:
  • Since it's an array,
  • So what is the compiled class name? What about the classpath?
  • Why is dynamic loading not suitable for arrays?
  • How to dynamically load an array?
  • Partial content reference
    • Writing high quality code (151 suggestions for improving Java programs)
    • Deep understanding of Java virtual machine

1, Since the array is a class, what is the compiled class name?

Through the following code, we can see that for the basic type array, it is compiled as [+ basic type ID, and for the reference type, it is [L + reference class path

package com.liruilong;

import java.util.logging.Logger;

/**
 * @Project_name: workspack
 * @Package: com.liruilong
 * @Description:
 * @Author: 1224965096@qq.com
 * @WeChat_Official_Accounts: The mountains and rivers are all right
 * @blog: https://liruilong.blog.csdn.net/
 * @Date: 2022/2/9  3:08
 */
public class ArrayDemo {
    static Logger logger = Logger.getAnonymousLogger();

    public static void main(String[] args) {
        logger.info("Compiled class name of basic type array:" + int[].class.getName());
        logger.info("Reference type array compiled class name:" + String[].class.getName());

    }

}

 

February 09, 2022 3:57:03 morning com.liruilong.ArrayDemo main
information: Compiled class name of basic type array:[I
February 09, 2022 3:57:03 morning com.liruilong.ArrayDemo main
information: Reference type array compiled class name:[Ljava.lang.String;

Process finished with exit code 0

In java, array is a special class. Whether it is a basic type array or a reference type array, there is no traceable class path

Array element type and compiled type

2, Why is dynamic loading not suitable for arrays

Dynamic loading

I won't say much about dynamic loading here. I'm sure you're familiar with small partners. When the original JDBC programming connects to the database, you usually dynamically load a driver class connecting to the database through static blocks. Class is used here Forname (driver), load the driver class into memory.

Of course, forName here only loads a class into memory, does not generate an instance object, and will not execute any methods. How to generate the object and register it with the DriverManager of the injected driver class can generally be realized by means of static blocks, that is, the instance object is generated and registered at the same time of class loading.

We know that in the last step of class loading (loading, verification, preparation, parsing and initialization), class initialization executes the < clinit > () method of class constructor, which is generated by the combination of the assignment actions of all class variables in the class and the statements in the static sentence block automatically collected by the compiler. The order in which the compiler collects is determined by the order in which the statement appears in the source file.

The following is the source code of mysql driver class

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.mysql.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

Why not for arrays

For dynamic loading, you can take a look at in-depth understanding of Java virtual machine and return to our question. Why arrays are not suitable for dynamic loading? From the above code, you can know that when you use forName to load a class, you need the full path or fully qualified name of a class.

However, whether it is a basic type array or a reference type array, there is no traceable class path and it is not a specific class. Therefore, an error Java. Net will be reported when loading lang.ClassNotFoundException

package com.liruilong;
import java.util.logging.Logger;

/**
 * @Project_name: workspack
 * @Package: com.liruilong
 * @Description:
 * @Author: 1224965096@qq.com
 * @WeChat_Official_Accounts: The mountains and rivers are all right
 * @blog: https://liruilong.blog.csdn.net/
 * @Date: 2022/2/9  3:08
 */
public class ArrayDemo {
    static Logger logger = Logger.getAnonymousLogger();

    public static void main(String[] args) throws ClassNotFoundException {
        Class.forName("java.lang.String[]");
        Class.forName("int[]");
    }

}

Exception in thread "main" java.lang.ClassNotFoundException: java/lang/String[]
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at com.liruilong.ArrayDemo.main(ArrayDemo.java:19)

Process finished with exit code 1

Direct loading is not possible. Is it feasible to load an array of compiled types? Let's see

package com.liruilong;
import java.util.logging.Logger;

/**
 * @Project_name: workspack
 * @Package: com.liruilong
 * @Description:
 * @Author: 1224965096@qq.com
 * @WeChat_Official_Accounts: The mountains and rivers are all right
 * @blog: https://liruilong.blog.csdn.net/
 * @Date: 2022/2/9  3:08
 */
public class ArrayDemo {
    static Logger logger = Logger.getAnonymousLogger();

    public static void main(String[] args) throws ClassNotFoundException {
        Class.forName("[Ljava.lang.String;");
        Class.forName("[I");
    }

}

Bad level value for property: .level
Bad level value for property: java.util.logging.ConsoleHandler.level

Process finished with exit code 0

From the above, we can know that you can load the compiled class path and dynamically load an object array, but it doesn't make sense. You cannot generate an instance object through the newInstance() method. In java, arrays are of fixed length, and arrays without length are not allowed to exist.

package com.liruilong;
import java.util.logging.Logger;

/**
 * @Project_name: workspack
 * @Package: com.liruilong
 * @Description:
 * @Author: 1224965096@qq.com
 * @WeChat_Official_Accounts: The mountains and rivers are all right
 * @blog: https://liruilong.blog.csdn.net/
 * @Date: 2022/2/9  3:08
 */
public class ArrayDemo {
    static Logger logger = Logger.getAnonymousLogger();

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<String[]> aClass = (Class<String[]>) Class.forName("[Ljava.lang.String;");
        String[] strings = aClass.newInstance();
    }

}

Bad level value for property: .level
Bad level value for property: java.util.logging.ConsoleHandler.level
Exception in thread "main" java.lang.InstantiationException: [Ljava.lang.String;
	at java.lang.Class.newInstance(Class.java:427)
	at com.liruilong.ArrayDemo.main(ArrayDemo.java:20)
Caused by: java.lang.NoSuchMethodException: [Ljava.lang.String;.<init>()
	at java.lang.Class.getConstructor0(Class.java:3082)
	at java.lang.Class.newInstance(Class.java:412)
	... 1 more

Process finished with exit code 1

3, How to dynamically load an array

How to generate an Array in a way similar to dynamic loading? We can use the Array tool class to dynamically load an Array.

package com.liruilong;
import java.lang.reflect.Array;
import java.util.logging.Logger;

/**
 * @Project_name: workspack
 * @Package: com.liruilong
 * @Description:
 * @Author: 1224965096@qq.com
 * @WeChat_Official_Accounts: The mountains and rivers are all right
 * @blog: https://liruilong.blog.csdn.net/
 * @Date: 2022/2/9  3:08
 */
public class ArrayDemo {
    static Logger logger = Logger.getAnonymousLogger();

    public static void main(String[] args)  {
        String [] strings = (String[]) Array.newInstance(String.class,6);
        logger.info("String Array length:"+strings.length);
        int[][] ints = (int [][])Array.newInstance(int.class,6,3);
        logger.info("int Array length:"+ints.length);
    }

}

 

Bad level value for property: .level
Bad level value for property: java.util.logging.ConsoleHandler.level
Can't set level for java.util.logging.ConsoleHandler
February 09, 2022 5:15:12 morning com.liruilong.ArrayDemo main
information: String Array length: 6
February 09, 2022 5:15:12 morning com.liruilong.ArrayDemo main
information: int Array length: 6

Process finished with exit code 0

Looking at the source code, we will find that this is a local method, which is implemented in languages such as C or C + +

 public static Object newInstance(Class<?> componentType, int length)
        throws NegativeArraySizeException {
        return newArray(componentType, length);
    }
private static native Object newArray(Class<?> componentType, int length)
        throws NegativeArraySizeException;

About the dynamic loading of arrays and sharing with friends here, come on^_^

 

Click follow to learn about Huawei's new cloud technology for the first time~

Keywords: Java

Added by usamaalam on Fri, 11 Feb 2022 23:02:40 +0200