Java反射

一、概述

当在程序运行期间,对于任意一个类,都能够知道这个类的所有属性与方法,对于任意一个对象,都能够调用它的任意一个属性与方法,这种动态获取信息与动态调用对象的方法的机制就是反射机制。当然,前提条件是必须拿到类的.class对象。至于这个class对象,其实是在jvm中,由类加载器根据类的全限定名来读取对应类的二进制字节流,并且转化为一个与目标类型对应的java.lang.Class对象实例

二、方式

@Data
class Person {
    private String userName;
    private int age;

    public void print(String parameter){
        System.out.println(parameter);
    }
    public void noParameterPrint(){
        System.out.println("没参数的方法");
    }
    public static void staticFunction(){
        System.out.println("没参数的静态方法");
    }
}

1、对象调用getClass()方式

Person person = new Person();
Class<? extends Person> clazz = person.getClass();
Arrays.asList(clazz.getDeclaredFields()).forEach(item -> {
    System.out.println(item.getType() + "-------" + item.getName());
});

2、类名.class

Class<? extends Person> clazz2 = Person.class;
Arrays.asList(clazz2.getDeclaredFields()).forEach(item -> {
    System.out.println(item.getType() + "-------" + item.getName());
});

3、Class.forName()

try {
    Class<?> clazz3 = Class.forName("com.example.reflect.test.Person");
    Arrays.asList(clazz2.getDeclaredFields()).forEach(item -> {
        System.out.println(item.getType() + "-------" + item.getName());
    });
    try {
        Method print = clazz3.getDeclaredMethod("print", String.class);
        Method noParameterPrint = clazz3.getDeclaredMethod("noParameterPrint");
        Method staticFunction = clazz3.getDeclaredMethod("staticFunction");
        Object instance = clazz3.newInstance();
        print.invoke(instance, "动态调用有参数的方法");
        noParameterPrint.invoke(instance);
        // 静态方法可以直接传实例或者null
        staticFunction.invoke(null);
        staticFunction.invoke(instance);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
        e.printStackTrace();
    }
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

三、常用api

getName():获得类的完整名字。

getFields():获得类的public类型的属性。

getDeclaredFields():获得类的所有属性。包括private 声明的和继承类

getMethods():获得类的public类型的方法(包括父类的)。

getDeclaredMethods():获得类的所有方法(不包括父类的)。

getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。

getConstructors():获得类的public类型的构造方法。

getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。

newInstance():通过类的构造方法创建这个类的一个对象实例。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值