首页 > 技术文章 > java 反射

kikyoqiang 2020-10-17 22:14 原文

反射

package model;

import java.lang.reflect.*;
import java.util.Date;

public class Person {
    public static void main(String[] args) throws Exception {
        Class personClass = Person.class;
        Object instance = personClass.newInstance();

        System.out.println("*****************获取公有、无参的构造方法*************");
        Constructor con = personClass.getConstructor(null);
        //1>、因为是无参的构造方法所以类型是一个null,不写也可以:这里需要的是一个参数的类型,切记是类型
        //2>、返回的是描述这个无参构造函数的类对象。

        System.out.println("*************获取公有字段**并调用*****************");
        Field f = personClass.getField("age");
        System.out.println(f);


        System.out.println("*************获取公有方法并调用*****************");
        Method m2 = personClass.getMethod("sayHello2", String.class);
        Object invoke = m2.invoke(instance, new String[]{" aaa"});
        System.out.println(invoke);

        System.out.println("***************获取私有的方法******************");
        Method m3 = personClass.getDeclaredMethod("sayHello3", String.class);
        m3.setAccessible(true);
        Object invoke1 = m3.invoke(instance, new String[]{"vvv"});
        System.out.println(invoke1);
    }

    private Integer id;
    private String name;
    private Integer sex;
    private Date birth;
    public int age;

    public Person() {
    }

    public Person(Integer id, String name, Integer sex, Date birth, int age) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.birth = birth;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public int getAge() {
        return age;
    }

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

    public void sayHello() {
        System.out.println("hello");
    }

    public String sayHello2(String name) {
        return "hello" + name;
    }

    private String sayHello3(String name) {
        return "hello " + name;
    }

}

推荐阅读