反射入门_入门教程

反射入门_入门教程反射package com.atguigu.java;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Person { private String name; public int age; public Person() { } public void setName(S

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

反射

package com.atguigu.java;

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

public class Person { 
   
    private String name;
    public int age;

    public Person() { 
   
    }

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

    @Override
    public String toString() { 
   
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

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

    public String getName() { 
   
        return name;
    }

    public int getAge() { 
   
        return age;
    }

    public Person(String name, int age) { 
   
        this.name = name;
        this.age = age;
    }
    private Person(String name) { 
   
        this.name = name;
    }
    public void show(){ 
   
        System.out.println("您好,我是一个人");
    }
    private String showNation(String nation){ 
   
        System.out.println("我的国籍是" + nation);
        return nation;
    }

    public static void main(String[] args) throws Exception { 
   
        Class clazz = Person.class;
// 1.通过反射创建对象
        Constructor cons = clazz.getConstructor(String.class,int.class);
        Object obj = cons.newInstance("Tom",12);
        Person p = (Person) obj;
        System.out.println(obj.toString());


// 2.通过反射,使用对象指定的方法和属性
        Field age = clazz.getDeclaredField("age");
        age.set(person,10);
        System.out.println(p.toString());

// 3.调用方法
        Method show = clazz.getMethod("show");
        show.invoke(p);
    }
}

通过反射可以调用私有的构造器和方法

public static void main(String[] args) throws Exception { 
   
        //私有属性
        Class clazz = Person.class;
        Constructor cons1 = clazz.getDeclaredConstructor(String.class);
        cons1.setAccessible(true);
        Person p = (Person) cons1.newInstance("Jerry");
        System.out.println(p);
        //私有方法
        Method showNation = clazz.getDeclaredMethod("showNation", String.class);
        showNation.setAccessible(true);
        String nation = (String) showNation.invoke(p,"中国");
        System.out.println(nation);

    }

Class类的理解

  1. 类的加载过程:程序经过javac命令后会生成一个或多个.class文件。java命令对某个字节码文件进行解释运行,相当于将某个字节码文件加载到内存中。加载到内存中的类。我们就成为运行时类,此运行时类,就作为一个Class的一个实例。
  2. Class类对应一个运行时类。

Class实例的获取(4种)

public static void main(String[] args) throws Exception { 
   
// 1.
        Class clazz1 = Person.class;
        System.out.println(clazz1);

// 2.
        Person p1 = new Person();
        Class clazz2 = p1.getClass();
        System.out.println(clazz2);

// 3.
        Class clazz3 = Class.forName("com.atguigu.java.Person");
        System.out.println(clazz3);

// 4.
        ClassLoader classLoader = Person.class.getClassLoader();
        Class clazz4 = classLoader.loadClass("com.atguigu.java");
        System.out.println(clazz4);
    }

类(外部类,内部类,匿名内部类等等),接口,数组,enum,注解,基本数据类型 ,void都算Class对象

3种类加载器

  1. 引导类加载器:负责java核心类库的加载,无法获得.
  2. 扩展类加载器:负责jre/lib/text目录下的类的加载
  3. 系统类加载器:自定义的类的加载器,也是最常用的加载器

使用类加载器读取配置文件

public static void main(String[] args) throws Exception { 
   
        Properties pros = new Properties();
        ClassLoader classLoader = Person.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("jdbc.properties");
        pros.load(is);
        String user = pros.getProperty("user");
        System.out.println(user);
    }

获取运行时类的完整结构

1. 属性

public static void main(String[] args) { 
   
        Class clazz = Person.class;
        //获取当前类和其父类的所生命的public属性
        Field[] fields = clazz.getFields();
        for(Field field : fields){ 
   
            System.out.println(field);
        }
        //获取当前运行时类的所有属性,不包含父类。
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f :declaredFields){ 
   
            System.out.println(f);
        }
        //权限修饰符 数据变量 变量名
        Field[] declaredFields1 = clazz.getDeclaredFields();
        for (Field f : declaredFields1){ 
   
            //1.权限修饰符
            int modifier = f.getModifiers();
            System.out.println(Modifier.toString(modifier));
            //2.数据类型
            Class type = f.getType();
            System.out.println(type.getName());
            //变量名
            System.out.println(f.getName());

        }
    }

2. 方法

public static void main(String[] args) { 
   
        //当前类和其父类所有的public方法
        Class clazz = Person.class;
        Method[] methods = clazz.getMethods();
        for(Method m : methods){ 
   
            System.out.println(m);
        }

        System.out.println();

        //获取当前类所声明的所有方法:
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for(Method m : declaredMethods){ 
   
            System.out.println(m);
        }
    }

3. 注解

public static void main(String[] args) { 
   
        Class clazz = Person.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for(Method m : declaredMethods){ 
   
            //获取方法的注解
            Annotation[] annos = m.getAnnotations();
            for(Annotation a : annos){ 
   
                System.out.println(a);
            }
            //权限修饰符
            System.out.print(Modifier.toString(m.getModifiers()) + "\t");
            //返回值类型
            System.out.print(m.getReturnType().getName() + "\t");
            //方法名
            System.out.print(m.getName());
            System.out.print("(");
            //形参列表
            Class[] parameterTypes = m.getParameterTypes();
            if(!(parameterTypes == null && parameterTypes.length != 0))
            { 
   
                for(int i = 0;i < parameterTypes.length;i ++){ 
   
                    if(i == parameterTypes.length - 1){ 
   

                        System.out.print(parameterTypes[i].getName() + " args_" + i );
                    }
                    System.out.print(parameterTypes[i].getName() + " args_" + i + " , ");
                }
            }
            System.out.print(")");
            //抛出异常
            Class[] exceptionTypes = m.getExceptionTypes();
            if(!(exceptionTypes == null || exceptionTypes.length == 0)){ 
   
                System.out.print(" throus ");
                for(int i = 0;i < exceptionTypes.length;i ++) { 
   
                    if (i == exceptionTypes.length - 1) { 
   
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }
                    System.out.print(exceptionTypes[i].getName() + " , ");

                }

            }
            System.out.println();
        }

    }

4.构造器

public static void main(String[] args) throws Exception { 
   
        Class clazz = Person.class;
        //当前运行时类中声明为public构造器
        Constructor[] constructors = clazz.getConstructors();
        for(Constructor c : constructors){ 
   
            System.out.println(c);
        }
        System.out.println();
        //获取当前运行时类中声明的所有构造器
        Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
        for(Constructor c : declaredConstructors){ 
   
            System.out.println(c);
        }
    }

5.泛型接口

public static void main(String[] args) throws Exception { 
   
        Class clazz = Person.class;
        Type genericSuperclass = clazz.getGenericSuperclass();
        System.out.println(genericSuperclass);


        Type genericSuperclass1 = clazz.getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) genericSuperclass1;
        //获取泛型类型
        Type[] actualTypeArguments = paramType.getActualTypeArguments();
        System.out.println(((Class)actualTypeArguments[0]).getName());



    }

6.接口,包,注解

public static void main(String[] args) throws Exception { 
   
        Class clazz = Person.class;
        Class[] interfaces = clazz.getInterfaces();
        for(Class c : interfaces){ 
   
            System.out.println(c);
        }
        System.out.println();
        //获取运行时类的父类实现的接口
        Class[] interfaces1 = clazz.getSuperclass().getInterfaces();

        for(Class c : interfaces1){ 
   
            System.out.println(c);
        }
        //运行时类所在包
        Package pack = clazz.getPackage();
        //运行时类的注解
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annos : annotations){ 
   
            System.out.println(annos);
        }
    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/168826.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • linux命令大全(手册)_Linux高频命令汇总

    linux命令大全(手册)_Linux高频命令汇总史上最全的Linux常用命令汇总(超全面!超详细!)收藏这一篇就够了!

    2022年8月22日
    3
  • 个人号微信api接口开发_API接口授权系统php源码

    个人号微信api接口开发_API接口授权系统php源码最近公司需求开发一套自定义的微信机器人,需求是可以自动聊天,自动回复,发朋友圈,转发语音,以及自动添加好友等,还可以取聊天内容保存自己数据库里,what????这怎么可能实现,一口回绝,当产品经理拿着现成的市场产品打在脸上的时候,才发现微信真的可以实现!!调研开发了3个月,3个月啊!!!(主要被各种技术走偏路),终于得到以下知识,都是走过的心酸泪,大家开发完成,记得给我点个赞!!!大家一般需求点无非是以下几个需求:1.开发个人微信营销系统2.开发自定义的微信机器人,3.开发微信智能聊天客服系统

    2022年10月1日
    0
  • 庆祝kkkbo出道!

    庆祝kkkbo出道!希望学编程有始有终,不做弱者,不做断者-常思华联兴之日子,多念华联兴之饭菜,忆图思苦,勉励自身。

    2022年7月3日
    41
  • Nagios3.0.5在CentOS5.2中安装[通俗易懂]

    Nagios3.0.5在CentOS5.2中安装

    2022年3月8日
    37
  • 程序员即装逼又实用的Cmd命令行

    程序员即装逼又实用的Cmd命令行首先windows键+R(+R)打开运行,输入cmd回车打开命令行。1、cleanmgr选择盘符清理垃圾,能加快电脑运行速度。2、chkdsk磁盘检查,能检查磁盘是否有损害。3、devmgmt打开设备管理器4、dxdiag打开DirectX诊断工具,买二手电脑是避免黑商修改电脑配5、ping:ping192.168.0.1判断某台电脑是否能连…

    2022年5月20日
    73
  • 大学四年,我把私藏的自学「学习网站/实用工具」都贡献出来了

    大学四年,我把私藏的自学「学习网站/实用工具」都贡献出来了在分享之前,先说说初学者如何学习编程,这个话题想必非常的重要,要学好编程,给你一些学习网站也好、实用工具也好,但前提是你知道如何去学习它。见过很多初学者,以及小鹿我刚开始学习的时候,也是自己瞎摸索,找不到路子,看什么书?看什么资料?编程的方向太多了,如果确定自己的方向?尤其是上大一、大二甚至大三还没有确定自己到底是学习前端还是后天,每天这学一点,那学一块,掌握那么多,没有一门精通的,去面试的时候…

    2022年6月12日
    31

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号