JAVA Constructor和动态实例化

概述

通过反射可以获取某类的 构造方法 信息,构造方法 对应的类是 Constructor类,构造方法 的信息封装在 Constructor 类对象中

获取 Constructor 类对象

通过Class类的以下方法:

  • getConstructor(Class...<?> parameterTypes) 获得该类中与参数类型匹配的公有构造方法
  • getConstructors() 获得该类的所有公有构造方法
  • getDeclaredConstructor(Class...<?> parameterTypes) 获得该类中与参数类型匹配的构造方法
  • getDeclaredConstructors() 获得该类所有构造方法

例子:
如果是访问指定的构造方法,需要根据该构造方法的入口参数的类型来访问。例如,访问一个入口参数类型依次为 int 和 String 类型的构造方法,下面的两种方式均可以实现。

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

Constructor 类常用方法

  • isVarArgs() 查看该构造方法是否允许带可变数量的参数,如果允许,返回 true,否则返回false
  • getParameterTypes() 按照声明顺序以 Class 数组的形式获取该构造方法各个参数的类型
  • getExceptionTypes() 以 Class 数组的形式获取该构造方法可能抛出的异常类型
  • newInstance(Object … initargs) 通过该构造方法利用指定参数创建一个该类型的对象,如果未设置参数则表示采用默认无参的构造方法
  • setAccessiable(boolean flag) 如果该构造方法的权限为 private,默认为不允许通过反射利用 netlnstance()方法创建对象。如果先执行该方法,并将入口参数设置为 true,则允许创建对象
  • getModifiers() 获得可以解析出该构造方法所采用修饰符的整数通过 java.lang.reflect.Modifier 类可以解析出 getMocMers() 方法的返回值所表示的修饰符信息。在该类中提供了一系列用来解析的静态方法,既可以查看是否被指定的修饰符修饰,还可以字符串的形式获得所有修饰符。表图2 列出了 Modifier 类的常用静态方法。

Modifier类的常用方法

  • isStatic(int mod) 如果使用 static 修饰符修饰则返回 true,否则返回 false
  • isPublic(int mod) 如果使用 public 修饰符修饰则返回 true,否则返回 false
  • isProtected(int mod) 如果使用 protected 修饰符修饰则返回 true,否则返回 false
  • isPrivate(int mod) 如果使用 private 修饰符修饰则返回 true,否则返回 false
  • isFinal(int mod) 如果使用 final 修饰符修饰则返回 true,否则返回 false
  • toString(int mod) 以字符串形式返回所有修饰符

例如,下列代码判断对象 con 所代表的构造方法是否被 public 修饰,以及以字符串形式获取该构造方法的所有修饰符。
int modifiers = con.getModifiers(); // 获取构造方法的修饰符整数
boolean isPublic = Modifier.isPublic(modifiers); // 判断修饰符整数是否为public
string allModifiers = Modifier.toString(modifiers);

例子:

打印构造方法信息

定义类

public class Student3 {
    String name;
    int age;

    public Student3(String name, int age) throws NullPointerException{
        this.name=name;
        this.age=age;
    }
}

定义测试类

public class Test3 {
    public static void main(String[] args) {
        printInfo(Student3.class);
    }

    static void printInfo(Class cls) {
        System.out.println("构造方法:");
        Constructor[] cons=cls.getDeclaredConstructors();
        for(Constructor con:cons){
            System.out.println(con.getName());
            System.out.println("构造方法形参类型:");
            // 获取所有参数类型
            Class[] parameterTypes = con.getParameterTypes();
            for (Class p:parameterTypes) {
                System.out.println(" " + p.getSimpleName());
            }
            System.out.println("构造方法拋出异常:");
            // 获取所有可能拋出的异常类型
            Class[] exceptionTypes = con.getExceptionTypes();
            for (Class e:exceptionTypes) {
                System.out.println(" " + e.getSimpleName());
            }
        }
    }

}

可以打印构造方法信息

动态实例化

定义类

public class Student3 {
    String name;
    int age;

    public Student3(String name, int age) throws NullPointerException{
        this.name=name;
        this.age=age;
    }
}

定义测试类,动态实例化

public class Test31 {
    public static void main(String[] args) {
        try {
            Object obj=newInstance("reflect.Student3");
            printFieldInfo(obj);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    static Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
        Class cls=Class.forName(className);
        Constructor[] cons=cls.getDeclaredConstructors();

        Object obj=cons[0].newInstance("鹿晗",20);
        return obj;
    }
    static void printFieldInfo(Object obj) throws IllegalAccessException {

        System.out.println("成员变量信息:");
        Field[] fields=obj.getClass().getDeclaredFields();
        for(Field f:fields){
            Class type=f.getType();
            Object value=f.get(obj);
            System.out.println(type.getSimpleName()+" "+f.getName()+"="+value);
        }
    }
}

感谢:
https://www.jianshu.com/p/9be58ee20dee


原文出处:/show_1EF4tKXUgX0S.html