反射

 

反射机制

对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

获取class的三种方式

方式一: 通过Object类中的getObject()方法

Person p = new Person();

Class c = p.getClass();

 

方式二: 通过 类名.class 获取到字节码文件对象(任意数据类型都具备一个class静态属性,看上去要比第一种方式简单)。

Class c2 = Person.class;

 

方式三: 通过Class类中的方法(将类名作为字符串传递给Class类中的静态方法forName即可)。

Class c3 = Class.forName("Person");

 通过反射获取构造方法并使用

l  返回一个构造方法

n  public Constructor<T> getConstructor(Class<?>... parameterTypes) 获取public修饰, 指定参数类型所对应的构造方法

n  public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 获取指定参数类型所对应的构造方法(包含私有的)

 

l  返回多个构造方法

n  public Constructor<?>[] getConstructors() 获取所有的public 修饰的构造方法

n  public Constructor<?>[] getDeclaredConstructors() 获取所有的构造方法(包含私有的)

 

代码展示

publicclass ReflectDemo {

    publicstaticvoid main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException {

        //获取Class对象

        Class c = Class.forName("cn.oracle_01_Reflect.Person");//包名.类名

       

        //获取所有的构造方法

        //Constructor[] cons = c.getConstructors();

        Constructor[] cons = c.getDeclaredConstructors();

        for (Constructor con : cons) {

           System.out.println(con);

        }

       

        System.out.println("------------------------");

        //获取一个构造方法

        //public Person()

        Constructor con1 = c.getConstructor(null);

        System.out.println(con1);

       

        //public Person(String name)

        Constructor con2 = c.getConstructor(String.class);

        System.out.println(con2);

       

        //private Person(String name, int age)

        Constructor con3 = c.getDeclaredConstructor(String.class, int.class);

        System.out.println(con3);

       

        //public Person(String name, int age, String address)

        Constructor con4 = c.getDeclaredConstructor(String.class, int.class, String.class);

        System.out.println(con4);

    }

}

 

 通过反射方式,获取私有构造方法,创建对象

publicclass ConstructorDemo2 {

    publicstaticvoid main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        //1,获取到Class对象

        Class c = Class.forName("cn.oracle_01_Reflect.Person");//包名.类名

       

        //2,获取指定的构造方法

        //private Person(String name, int age)

        Constructor con = c.getDeclaredConstructor(String.class, int.class);

       

        //3,暴力反射

        con.setAccessible(true);//取消 Java 语言访问检查

       

        //4,通过构造方法类中的功能,创建对象

        Object obj = con.newInstance("小明", 23);

        System.out.println(obj);

       

    }

}

原文地址:https://www.cnblogs.com/1997WY/p/10708921.html