栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【7.20】反射

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【7.20】反射

反射 1. 反射机制的概念

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

2. 反射机制的作用
  • 在运行时判断任意一个对象所属的类。
  • 在运行时构造任意一个类的对象。
  • 在运行时判断任意一个类所具有的成员变量和方法。
  • 在运行时调用任意一个对象的方法。
3. 反射机制的理解

反射是java语言的一个特性,它允程序在运行时(注意不是编译的时候)来进行自我检查并且对内部的成员进行操作。

4. Class类的使用

用于获得类的Class对象

5. Class文件获取的三种方式
  • 通过对象的getClass()方法获得该对象所属的类
    Student student = new Student();
    Class class1 = student.getClass();
  • 通过类的class属性获得
    Class class2 = Student.class;
  • 通过类的完整包名加类名获得
    Class class3 = Class.forName(“反射.Student”);
6. 获取Constructor对象

获得公有的构造方法对象。

Constructor[] constructors = class1.getConstructors();
7. 获取私有Constructor对象

获得全部的构造对象,包括私有的。

        Constructor[] declaredConstructors = class1.getDeclaredConstructors();
        for (Constructor declaredConstructor : declaredConstructors) {
            if(declaredConstructor.getModifiers()==2){
                System.out.println("这是私有构造方法");
            }
        }

根据modifiers属性获得修饰词

public:Modifier.PUBLIC (0x00000001) (1)
private:Modifier.PRIVATE (0x00000002) (2)
protected:Modifier.PROTECTED (0x00000004) (4)
8. 获取Method对象
Method[] methods = class1.getMethods();
9. 获取私有Method对象
        Method[] declaredMethods = class1.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            if(declaredMethod.getModifiers()==2)
            {
                System.out.println("私有方法:"+declaredMethod.getName());
            }
        }
10. Constructor的使用
  • 通过Constructor的newInstance()方法构造对象。
        Constructor nonArgsConstructor = class1.getConstructor();
        Student student1 = nonArgsConstructor.newInstance();

  • getName();获得方法名。
  • getModifiers();获得修饰符。
  • getParamenterTypes();获得构造方法的参数类型。
11. Method类的使用
  • invoke()执行某个对象的方法。有参数后面可以加参数。
    declaredMethod.invoke(student);
  • 一些重要的属性
private String              name;//类名
private Class            returnType;//返回值类型
private Class[]          parameterTypes;//参数类型
private Class[]          exceptionTypes;//异常类型
private int                 modifiers;//作用域
12. Field类的使用

Field类可以获得字段的属性。

    private String              name;//方法名
    private Class            type;//方法类型
    private int                 modifiers//方法作用域
13. Modifier类的介绍

用来描述修饰符的。

    public static final int PUBLIC           = 0x00000001;
    public static final int PRIVATE          = 0x00000002;
    public static final int PROTECTED        = 0x00000004;
    public static final int STATIC           = 0x00000008;
    public static final int FINAL            = 0x00000010;
    public static final int SYNCHRONIZED     = 0x00000020;
14. 反射使用练习
public class SolutionReflect {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException {
        //1、通过对象获取完整的包名和类名
        System.out.println("获取Student类的包名:");
        Student student = new Student();
        System.out.println(student.getClass().getPackage()+""+student.getClass().getName());
        //2、实例化Class类对象
        Class aClass = Class.forName("com.fiber.Student");
        //3、通过Class实例化其他类对象
        Student student1 = (Student) aClass.newInstance();
        //4、通过Class调用其他类中的构造函数
        Constructor constructor = aClass.getConstructor();
        //5、获取一个类实现的接口
        System.out.println("打印ArrayList的接口");
        for (Class anInterface : ArrayList.class.getInterfaces()) {
            System.out.println(anInterface.getPackage()+" "+anInterface.getName());
        }
        //6、获取某个类的父类
        System.out.println("打印ArrayList的父类");
        System.out.println(ArrayList.class.getSuperclass());
        //7、获取某个类的全部构造函数
        System.out.println("得到Student类的全部构造方法,参数");
        for (Constructor declaredConstructor : aClass.getDeclaredConstructors()) {
            System.out.println(Arrays.toString(declaredConstructor.getParameterTypes()));
        }
        //8、获取某个类的全部属性
        System.out.println("得到Student类的所有属性");
        for (Field declaredField : aClass.getDeclaredFields()) {
            System.out.println(declaredField.getName());
        }
        //9、调用某个类的set和get方法
        Method studentSetAge = aClass.getMethod("setAge",int.class);
        studentSetAge.invoke(student,26);
        Method studentGetAge = aClass.getMethod("getAge");
        System.out.println(studentGetAge.invoke(student));
        //10、操作对象属性
        Field student1Name = aClass.getDeclaredField("name");
        student1Name.setAccessible(true);
        student1Name .set(student1,"Henry");
        System.out.println(student1Name.get(student1));
    }
}

15. 反射机制在工厂设计模式中的应用

某些接口具有较多的实现类或者某些类有较多的子类。
通过静态工厂方法创造这些类时需要进行大量的判断,是否复杂。
此时可以通过反射得到这些类的的构造方法,然后通过多态得到实例对象。

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException {
        List list1 = listFactory("java.util.ArrayList");
        List list2 = listFactory("java.util.Vector");
        List list3 = listFactory("java.util.LinkedList");
        System.out.println(list1.getClass().getName());
        System.out.println(list2.getClass().getName());
        System.out.println(list3.getClass().getName());
    }

    public static List listFactory(String classname){
        List list =null;
        try {
            list = (List)Class.forName(classname).newInstance();
        }
        catch (Exception e) {
                e.printStackTrace();
        }
        return list;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020585.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号