反射入门_入门教程

反射入门_入门教程反射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


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)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • [GBA ROM列表]不断补完中……

    [GBA ROM列表]不断补完中……出处:http://www.ezflash.cn/vbb/showthread.php?s=3a42901b8c2aacb56a02e61f690b8a05&threadid=14&perpage=15&pagenumber=10001-F-Zero(J)(最高时速)(J)RCG320002-SuperMarioAdvance(J)(超级马里奥A)(J)ACT32000

    2022年7月11日
  • git 修改用户名以及邮箱_git配置了用户名还要输入

    git 修改用户名以及邮箱_git配置了用户名还要输入1.查看gitconfiguser.name查看用户名gitconfiguser.email查看邮箱gitconfig–list也可以看到2.修改修改的话gitconfig–globaluser.name“xxx”修改用户名修改邮箱同理

    2022年9月4日
  • linux系统tcpdump指令抓包存为文件_tcpdump指定端口抓包

    linux系统tcpdump指令抓包存为文件_tcpdump指定端口抓包例:tcpdumphost172.16.29.40andport4600-X-s500tcpdupmhost172.16.29.40andport4600-X-s500-l-nn|teeldata.txt//可以将数据保存下来tcpdump采用命令行方式,它的命令格式为:tcpdump[-adeflnNOpqStvx][-c数量][-F…

    2022年8月20日
  • MYSQL8.0以上版本正确修改ROOT密码[通俗易懂]

    MYSQL8.0以上版本正确修改ROOT密码[通俗易懂]部署环境:安装版本redhatCent7.0MYSQL版本8.0.2.0成功部署完毕后出现故障情况:1.正常启动MYSQL服务后,敲Linux中root账户和密码进入不去。2.从/etc/my.cnf配置文件中加入skip-grant-table后正常登陆,但是不能创建用户等多操作总结来说:想进去mysql后不能操作多指令,操作多指令又不能进去mysql,死…

    2022年5月6日
  • startService与bindService的区别「建议收藏」

    startService与bindService的区别「建议收藏」Android执行Service有两种方法,一种是startService,一种是bindService。下面让我们一起来聊一聊这两种执行Service方法的区别。1、生命周期上的区别执行startService时,Service会经历onCreate->onStartCommand。当执行stopService时,直接调用onDestroy方法。调用者如果没有stopService,Servi

    2022年6月1日
  • HTML期末设计——代码篇[通俗易懂]

    HTML期末设计——代码篇[通俗易懂]事先声明这个网页设计也就是用了我学到的知识做的一个中规中矩的网页,可以给以后的大一新生们做个参考,和商业网站的效果肯定是没得比的,期望太高的可以关掉了,要严词批评我的请不要在我这说,当然,温柔的话,可以引入页效果图:<!DOCTYPEhtml><html> <head> <metacharset=”utf-8″> <title>欢迎来到香氛密语</title> <style>

    2022年6月14日

发表回复

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

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