程序员地瓜哥的小屋

Java中的反射

2021-07-07  本文已影响0人  CodingDGSun

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

如下代码示例:

package com.study.reflection;

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

    public Animal() {
        super();
    }

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

    public void eat() {

    }

    public String getInfo() {
        return "name:" + this.name + ", age:" + age;
    }
}
package com.study.reflection;

public class Cat extends Animal {
    public String color;
    private String owner;
    String sex;

    public Cat() {
        super();
    }

    public Cat(String name, int age, String color, String owner) {
        super(name, age);
        this.color = color;
        this.owner = owner;
    }

    public Cat(String owner) {
        this.owner = owner;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    void mie() {

    }

    private void smile() {
        System.out.println(name + "在笑");
    }

    public void cry() {
        System.out.println(name + "在哭");
    }

    @Override
    public String toString() {
        return "姓名:" + this.name + ", 年龄:" + this.age + ", 颜色:" + color + ", 主人:" + owner;
    }
}
package com.study.reflection;

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

public class TestReflect {
    public static void main(String[] args) {
        Class cat = null;
        try {
            cat = Class.forName("com.study.reflection.Cat");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //获取对象的所有公有(public)属性,例如:public String color;包括继承的父类中public修饰的属性
        Field[] fields = cat.getFields();
        for (Field f : fields) {
            //输出结果:
            // public java.lang.String com.study.reflection.Cat.color
            // public java.lang.String com.study.reflection.Animal.name
            // public int com.study.reflection.Animal.age
            System.out.println(f);
        }

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

        //获取对象所有属性(不管是public还是private或者没有修饰符的修饰的属性),但不包括继承的父类中的属性
        Field[] declaredFields = cat.getDeclaredFields();
        for (Field df : declaredFields) {
            //输出结果:
            //public java.lang.String com.study.reflection.Cat.color
            //private java.lang.String com.study.reflection.Cat.owner
            //java.lang.String com.study.reflection.Cat.sex
            System.out.println(df);
        }

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

        //获取对象的所有公共(public)方法;包括继承的父类中的public修饰的方法以及Object类中public修饰的方法
        Method[] methods = cat.getMethods();
        for (Method m : methods) {
            //输出结果:
            //public java.lang.String com.study.reflection.Cat.toString()
            //public void com.study.reflection.Cat.setColor(java.lang.String)
            //public java.lang.String com.study.reflection.Cat.getColor()
            //public void com.study.reflection.Cat.cry()
            //public void com.study.reflection.Animal.eat()
            //public java.lang.String com.study.reflection.Animal.getInfo()
            //public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
            //public final void java.lang.Object.wait() throws java.lang.InterruptedException
            //public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
            //public boolean java.lang.Object.equals(java.lang.Object)
            //public native int java.lang.Object.hashCode()
            //public final native java.lang.Class java.lang.Object.getClass()
            //public final native void java.lang.Object.notify()
            //public final native void java.lang.Object.notifyAll()
            System.out.println(m);
        }

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

        //获取对象所有方法(不管是public还是private或者没有修饰符的修饰的方法),但不包括继承的父类中的方法
        Method[] declaredMethods = cat.getDeclaredMethods();
        for (Method dm : declaredMethods) {
            //输出结果:
            //public java.lang.String com.study.reflection.Cat.toString()
            //public void com.study.reflection.Cat.setColor(java.lang.String)
            //public java.lang.String com.study.reflection.Cat.getColor()
            //void com.study.reflection.Cat.mie()
            //private void com.study.reflection.Cat.smile()
            //public void com.study.reflection.Cat.cry()
            System.out.println(dm);
        }

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

        //获取对象的所有公共(public)构造方法,但不包括继承的父类中的构造方法
        Constructor[] constructors = cat.getConstructors();
        for (Constructor c : constructors) {
            //输出结果:
            //public com.study.reflection.Cat(java.lang.String)
            //public com.study.reflection.Cat(java.lang.String,int,java.lang.String,java.lang.String)
            //public com.study.reflection.Cat()
            System.out.println(c);
        }

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

        //获取对象的所有构造方法,
        Constructor[] declaredConstructors = cat.getDeclaredConstructors();
        for (Constructor dc : declaredConstructors) {
            //输出结果:
            //public com.study.reflection.Cat(java.lang.String)
            //public com.study.reflection.Cat(java.lang.String,int,java.lang.String,java.lang.String)
            //public com.study.reflection.Cat()
            System.out.println(dc);
        }

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

        //Cat cat1 = (Cat) cat.newInstance();//此方法在Java9之后显示已过时
        Constructor<Cat> constructor = null;
        try {
            //获取全参数构造函数
            constructor = cat.getConstructor(String.class, int.class, String.class, String.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Cat cat1 = null;
        try {
            //使用构造函数赋值初始化
            cat1 = constructor.newInstance("花花", 2, "白色", "小明");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //输出结果:
        //姓名:花花, 年龄:2, 颜色:白色, 主人:小明
        System.out.println(cat1);

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

        //获取指定方法,并执行,【获取的方法必须是public修饰的】
        Method cry = null;
        try {
            //输出结果:
            //花花在哭
            cry = cat.getMethod("cry");//cry()方法
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        Object object = null;
        try {
            object = cry.invoke(cat1);//调用cry()方法
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读