阅读 1107

017 Java反射机制,一个实例讲述java反射的方法

太多的框架使用到Java的反射,彰显的Java反射异常重要。 反射是Java一个非常重要的高级特性。本章介绍一下Java反射。

Java反射机制是在程序运行过程中,对任何一个类,都能够知道它的所有属性和方法;并对这些属性和方法进行调用,称为动态调用,这种动态获取信息和动态调用对象方法的功能称为Java的反射机制。

Java反射机制主要功能:

  • 在运行时==判断任意一个对象所属的类。==
  • 在运行时==构造任意一个类的对象。==
  • 在运行时==判断任意一个类的所有成员变量和方法。==
  • 在运行时==调用任意一个对象的方法。==

一个示例讲述Java反射:

package com.lingyiwin.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TestReflect {
    public static void main(String[] args) throws Exception {
        Class student = null;

        try {
            student = Class.forName("com.lingyiwin.test.Student");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("获取student的所有共有属性");
        Field[] fields = student.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        System.out.println("\n获取student的所有属性,不包含继承的属性");
        Field[] declaredFields = student.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        System.out.println("\n获取student的所有公共方法");
        Method[] methods = student.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        System.out.println("\n获取student的所有公共方法,不包含继承的属性");
        Method[] declaredMethods = student.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }

        System.out.println("\n获取student的所有公共构造方法");
        Constructor[] declaredConstructors = student.getDeclaredConstructors();
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }

        System.out.println("\n使用默认构造函数实例化student.newInstance()  一定要有默认无参的构造函数。否则会报错");
        Student instance = (Student) student.newInstance();
        instance.setAddress("上海");
        System.out.println(instance.toString());

        System.out.println("\n使用构造函数 Student(String className) 实例化");
        Constructor constructor = student.getConstructor(String.class);
        Student st = (Student) constructor.newInstance("班级名称");
        System.out.println(st.toString());

        System.out.println("\n使用构造函数 Student(String name, int age, String className, String address) 实例化");
        Constructor ct = student.getConstructor(String.class, int.class, String.class, String.class);
        Student st1 = (Student) ct.newInstance("小明", 18, "班级名称", "上海");
        System.out.println(st1.toString());

        System.out.println("\n获取无参的方法并执行:");
        Method learn = student.getMethod("learn");
        learn.invoke(st1);

        System.out.println("\n获取有参的方法并执行:");
        Method readBook = student.getMethod("readBook",String.class);
        String str = (String) readBook.invoke(st1,"语文");
        System.out.println("方法返回值:" + str);
    }
}

复制代码
package com.lingyiwin.test;

public class Student extends Person implements Study {
    public String className;
    private String address;

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Student(String name, int age, String className, String address) {
        super(name, age);
        this.className = className;
        this.address = address;
    }

    public Student() {
    }

    public Student(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", className='" + className + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    @Override
    public void learn() {
        System.out.println("实现study接口");
    }

    public String readBook(String book) {
        System.out.println("学生读书");
        return this.name + "读" + book;
    }
}

复制代码
package com.lingyiwin.test;

public class Person {
    public String name;
    public int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person() {
        super();
    }

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String showInfo() {
        return "name:" + name + ",age:" + age;
    }
}

复制代码
package com.lingyiwin.test;

public interface Study {
    public void learn();
}

复制代码

众多方法,还请参考API,上面仅仅只有部分常用的。

文章分类
后端
文章标签