Java constructor by reflection access

In order to obtain dynamic information object constructor, first create a type of object or Constructor array by one of the following methods.

	getConstructors()
	
	getConstructor(Class<?>…parameterTypes)
	
	getDeclaredConstructors()
	
	getDeclaredConstructor(Class<?>...parameterTypes)

If the access structure is specified method, needs to be accessed according to the type of parameters of the entrance of the constructor. For example, an access type parameter inlet were int and String type of construction method, the following two methods may be implemented.

objectClass.getDeclaredConstructor(int.class,String.class);

objectClass.getDeclaredConstructor(new Class[]{int.class,String.class});

Each Constructor object constructor creates a representation, then use the method of operation Constructor object constructor.

Constructor class common method

Method name Explanation
isVarArgs() Check whether to allow the construction method with a variable number of parameters, if allowed, returns true, false otherwise
getParameterTypes() Obtaining the individual parameters of the constructor in declaration order in the form of an array type Class
getExceptionTypes() Get the exception type constructor may throw in the form of an array of Class
newInstance(Object … initargs) This creates a type object using the parameters specified by the constructor, if the parameter is not set indicates the default constructor with no arguments
setAccessiable(boolean flag) If the permission of the constructor is private, the default is not allowed to create an object by using reflection of netlnstance () method. If the method is performed first, and the inlet of the parameter set to true, the object is allowed to create
getModifiers() This configuration can be obtained by parsing method using integer modifier

Modifiers may parse the return values ​​getMocMers () method of the class represented by the java.lang.reflect.Modifier. Provides a series of static methods used to resolve in the class and can be viewed modifier whether a modification is specified, you can also get all the strings of modifiers.

Common methods of class Modifier

Static method name Explanation
isStatic(int mod) Returns If you are using a modified static modifier true, false otherwise
isPublic(int mod) Returns If you are using public modifier modified true, false otherwise
isProtected(int mod) Returns If you use the protected modifier modified true, false otherwise
isPrivate(int mod) Returns If you are using the private modifier modified true, false otherwise
isFinal (int mode) Returns If you are using the final modifier modified true, false otherwise
toString(int mod) Returns a string of all modifier

The following code determines the object constructor con is represented by the public if modified, the construction and method of obtaining a string of all modifiers.

int modifiers = con.getModifiers();    // 获取构造方法的修饰符整数
boolean isPublic = Modifier.isPublic(modifiers);    // 判断修饰符整数是否为public 
string allModifiers = Modifier.toString(modifiers);

Constructor class example of how to call a method of obtaining information on construction methods.

1. First create a Book class represents a book information. In this class declare a String variable represents the name of the book, two int variables represent the number of books and prices, and provides three constructors.

Book class final code as follows:

public class Book {
    String name; // 图书名称
    int id, price; // 图书编号和价格
    // 空的构造方法

    private Book() {
    }

    // 带两个参数的构造方法
    protected Book(String _name, int _id) {
        this.name = _name;
        this.id = _id;
    }

    // 带可变参数的构造方法
    public Book(String... strings) throws NumberFormatException {
        if (0 < strings.length)
            id = Integer.valueOf(strings[0]);
        if (1 < strings.length)
            price = Integer.valueOf(strings[1]);
    }

    // 输出图书信息
    public void print() {
        System.out.println("name=" + name);
        System.out.println("id=" + id);
        System.out.println("price=" + price);
    }
}

2. Write the test class Test, the class in the main () method to access by all constructors reflective Book class, and whether the construction method with a variable parameter type, parameter types, and the inlet may be thrown exception type information output to the console.

Test class code as follows:

public class Test {
    public static void main(String[] args) {
        // 获取动态类Book
        Class book = Book.class;
        // 获取Book类的所有构造方法
        Constructor[] declaredContructors = book.getDeclaredConstructors();
        // 遍历所有构造方法
        for (int i = 0; i < declaredContructors.length; i++) {
            Constructor con = declaredContructors[i];
            // 判断构造方法的参数是否可变
            System.out.println("查看是否允许带可变数量的参数:" + con.isVarArgs());
            System.out.println("该构造方法的入口参数类型依次为:");
            // 获取所有参数类型
            Class[] parameterTypes = con.getParameterTypes();
            for (int j = 0; j < parameterTypes.length; j++) {
                System.out.println(" " + parameterTypes[j]);
            }
            System.out.println("该构造方法可能拋出的异常类型为:");
            // 获取所有可能拋出的异常类型
            Class[] exceptionTypes = con.getExceptionTypes();
            for (int j = 0; j < exceptionTypes.length; j++) {
                System.out.println(" " + parameterTypes[j]);
            }
            // 创建一个未实例化的Book类实例
            Book book1 = null;
            while (book1 == null) {
                try { // 如果该成员变量的访问权限为private,则拋出异常
                    if (i == 1) {
                        // 通过执行带两个参数的构造方法实例化book1
                        book1 = (Book) con.newInstance("Java 教程", 10);
                    } else if (i == 2) {
                        // 通过执行默认构造方法实例化book1
                        book1 = (Book) con.newInstance();
                    } else {
                        // 通过执行可变数量参数的构造方法实例化book1
                        Object[] parameters = new Object[] { new String[] { "100", "200" } };
                        book1 = (Book) con.newInstance(parameters);
                    }
                } catch (Exception e) {
                    System.out.println("在创建对象时拋出异常,下面执行 setAccessible() 方法");
                    con.setAccessible(true); // 设置允许访问 private 成员
                }
            }
            book1.print();
            System.out.println("=============================\n");
        }
    }
}

3. Run the test class Test, the default constructor when reflection by Book Access (), see the output shown below.

查看是否允许带可变数量的参数:false
该构造方法的入口参数类型依次为:
该构造方法可能抛出的异常类型为:
在创建对象时抛出异常,下面执行setAccessible()方法
name = null
id = 0
price = 0
=============================

When reflected by the constructor Book two access parameters (String_name, int_id), you see the output shown below.

查看是否允许带可变数量的参数:false
该构造方法的入口参数类型依次为:
class java.lang.String
int
该构造方法可能抛出的异常类型为:
在创建对象时抛出异常,下面执行setAccessible()方法
name = null
id = 0
price = 0
=============================

When the number of variable parameters constructor Book (String ... strings) accessed by reflection, you will see the output shown below.

查看是否允许带可变数量的参数:true
该构造方法的入口参数类型依次为:
class java.lang.String;
该构造方法可能抛出的异常类型为:
class java.lang.String;
在创建对象时抛出异常,下面执行setAccessible()方法
name = null
id = 0
price = 0
=============================
Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104728094