反射1 - 基础

反射

对象获取自身的类对象

再通过类对象获取类中的属性、方法、权限等

public class _Reflect {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {

        User user = new Child();
        user.test1();

        //TODO .getClass() 获取对象的类对象
        Class<? extends User> aClass = user.getClass();

        //TODO .getName() .getSimpleName() 获取类对象 -- 类的名称
        System.out.println(aClass.getName()); //类的完整名称 - 包.类
        System.out.println(aClass.getSimpleName()); //类名 - 类
        System.out.println(aClass.getPackage()); //类的包名 - 包

        //TODO .getSuperclass() 获取类的父亲
        Class<?> superclass = aClass.getSuperclass();
        System.out.println(superclass);

        //TODO .getInterfaces() 获取类的接口 -- 可以有多个接口 -- 数组
        Class<?>[] interfaces = aClass.getInterfaces();
        System.out.println(interfaces.length);

        //TODO 获取类的属性
        Field f = aClass.getField("xxxx"); //public 修饰的指定属性
        Field f1 = aClass.getDeclaredField("xxxx"); //所有权限的指定属性

        Field[] fields = aClass.getFields(); //获取所有public属性 -- 数组
        Field[] declaredFields = aClass.getDeclaredFields(); //获取所有权限的所有属性

        //TODO 获取类的方法
        Method method = aClass.getMethod("xxxx");  //public + 指定方法
        Method method1 = aClass.getDeclaredMethod("xxxx"); //所有权限 + 指定方法

        Method[] methods = aClass.getMethods(); //public + 所有方法
        Method[] declaredMethods = aClass.getDeclaredMethods(); //所有权限 + 所有方法

        //TODO .getConstructor() 构造方法
        Constructor<? extends User> constructor = aClass.getConstructor();
        Constructor<?>[] constructors = aClass.getConstructors();
        
        Constructor<? extends User> declaredConstructor = aClass.getDeclaredConstructor();
        Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors();

        //TODO 获取权限(修饰符) -- 多个修饰符会融合成一个int值
        int modifiers = aClass.getModifiers();
        //TODO Modifier类提供方法通过 int 值判断权限
        boolean aPrivate = Modifier.isPrivate(modifiers);


    }
}

class User{
    public void test1(){

    }
}

class Child extends User{
    public void test2(){

    }
}
posted @   LaViez  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示