Java中的反射

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

如下代码示例:

  • 父类Animal
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;
    }
}
  • 子类Cat,继承Animal
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;
    }
}
  • 测试类TestReflect
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();
        }
    }
}
程序员地瓜哥的小屋 文章被收录于专栏

IT相关技术学习

全部评论

相关推荐

01-26 18:45
门头沟学院 Java
一天代码十万三:哥们实习再包一下吧,产出太笼统了,尽量体现业务
点赞 评论 收藏
分享
hanliu:1. 排版与格式问题字体与对齐问题:标题和内容的字体大小差异不够明显,无法迅速吸引目光。某些文字看起来有些拥挤(比如校园经历中的“班委成员”部分)。2. 内容逻辑性模块顺序问题:实习经历放在较靠后的位置,实际上这部分内容对应聘来说更重要,建议提前突出。细节表述不够突出:比如教育背景部分的专业课程仅仅列出名字,没有说明自己在这些课程中表现如何或者掌握了什么技能,缺乏量化描述。多余内容:例如“班委成员”和“宣传委员”这类校园经历,叙述过于普通,缺乏和岗位相关的实质性贡献。,建议简写。3. 措辞专业性表达不够精准:例如“协助班长与团支书更好地为同学服务”显得较为笼统,没有实际成果的体现。用词重复:如“学习了焊接”“学习了光检”等重复词语较多,缺乏丰富的动词来展示个人能力(如“负责”“优化”“改进”等)。技能展示不足:虽然列出了UG和CAD证书,但没有明确提到这些技能如何在实际工作中发挥作用。4. 技能匹配度技能深度不足:虽然列出了掌握的软件和技术,但没有描述技能水平(如“熟练掌握”“精通”),也没有具体案例支持这些技能。缺乏岗位导向性:比如针对机械设计与制造方向,实习经历提到了“E6尾灯项目”,但没有详细说明自己在其中的技术贡献,可能会显得经验描述泛泛而谈。5. 自我评价问题表达空泛:如“具有良好的沟通协调能力”“责任心强”之类的描述太常见,没有让人眼前一亮的特点。缺乏成果支持:自我评价中的能力没有用具体项目、经历或成就来验证,可信度较弱。 兄弟加油
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务