反射知识总结

package com.atguigu.spingcloud.bean;


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

/**
 * @FileName: ClassStudy
 * @Author Steven
 * @Date: 2020/3/27
 */
public class ClassStudy {

    public static void main(String[] args) throws Exception {

        //relectType();
        relectClass();

    }

    /**
     * 反射的三种类型
     * 1. Class.forName("");全限定名
     * 2.XXX.class;
     * 3.一个实体类引用getClass();
     */
    public static void relectType() throws ClassNotFoundException {
        Class aClass1 = Class.forName("com.atguigu.spingcloud.bean.Payment");
        Class aClass2 = Payment.class;
        Payment payment=new Payment();
        Class aClass3 = payment.getClass();
        System.out.println(aClass1);
        System.out.println(aClass2);
        System.out.println(aClass3);

    }


    /**
     * getFields();获取所有public的字段
     * getDeclaredFields();获取所有字段
     * 
     * getMethods();获取所有public的方法
     * getDeclaredMethod();获取所有public的方法
     * 
     * 
     * getDeclaredConstructor();获取构造方法
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws InstantiationException
     */
    public static void relectClass() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class aClass = Payment.class;
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            System.out.println(name);
            System.out.println(declaredField);
        }

        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            declaredMethod.setAccessible(true);
            String name = declaredMethod.getName();
            System.out.println(name);
            System.out.println(declaredMethod);
        }
        
        Constructor declaredConstructor = aClass.getDeclaredConstructor(Long.class, String.class);
        Object steven = declaredConstructor.newInstance(23L, "Steven");
        System.out.println(steven);


    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值