反射入门_入门教程

反射入门_入门教程反射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)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • Java volatile源码分析

    Java volatile源码分析synchronized是阻塞式同步,在线程竞争激烈的情况下会升级为重量级锁,而volatile可以说是JVM提供的最轻量级的同步机制。jMM告诉我们,各个线程会将共享变量从主内存中拷贝到工作内存,然后执行引擎会基于工作内存中的数据进行操作处理。线程在工作内存进行操作后什么时候写回到主内存中,实际上没有明确的限制。而针对volatile修饰的变量给java虚拟机特殊的约定,线程对volatile变量的修改会立刻被其他线程所感知,即不会出现数据脏读,从而保证数据的一个可见性。https://blog.

    2022年7月18日
  • 详解LK光流法(含金字塔多层光流),反向光流法(附代码)「建议收藏」

    详解LK光流法(含金字塔多层光流),反向光流法(附代码)「建议收藏」LK光流法可用来跟踪特征点的位置。比如在img1中的特征点,由于相机或物体的运动,在img2中来到了不同的位置。后面会称img1为Template(T),img2为I。光流法有个假设:灰度不变假设:同一个空间点的像素灰度值,在各图像中是不变的,也就是说T中特征点处的灰度,到了I中仍然是一样的灰度。这就要求光照恒定,物体反射恒定,是个很强的假设。现在要估计的是运动偏移量[dx,dy],也就是光流。仅用一个点无法解,一般会取一个窗口内的像素,考虑它们具有相同的运动。用最小二乘法来解像素的运动如下:

    2022年7月23日
  • 狂神说Linux_狂神说docker笔记

    狂神说Linux_狂神说docker笔记Linux在服务器端,很多大型项目都是部署在Linux服务器上利用VM + Centos7搭建本地Linux系统你可以使用 man [命令]来查看各个命令的使用文档,如 :man cp。概念云服务器就是一个远程电脑Linux中一切皆文件根目录/,所有的文件都挂载在这个节点下/bin:bin是Binary的缩写, 这个目录存放着最经常使用的命令。/boot: 这里存放的是启动Linux时使用的一些核心文件,包括一些连接文件以及镜像文件。/dev : dev是Device(设备

    2022年8月9日
  • 散列函数

    散列函数    在线性表和树表中的查询中,记录在表的位置跟记录的关键字之间不存在确定关系,也就是说在线性表和树表中查询通常要依托关键字比较,查找的效率取决于比较次数。    散列函数:一个把查找表中的关键字映射成该关键字对应的地址函数,记为Hash(key)=Addr。这里的地址可以是数组下标,索引,或内存地址等。散列函数可能将两个或两个以上的不同关键字映射到同一个地址,称这种情况为“冲突”。(假若这个函…

    2022年5月14日
  • idea激活码2021.5.3【在线注册码/序列号/破解码】

    idea激活码2021.5.3【在线注册码/序列号/破解码】,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月17日
  • Java8 CompletableFuture 用法全解

    Java8 CompletableFuture 用法全解目录一、创建异步任务1、Future.submit2、supplyAsync/runAsync二、异步回调1、thenApply/thenApplyAsync2、thenAccept/thenRun3、exceptionally4、whenComplete5、handle三、组合处理1、thenCombine/thenAcceptBoth/runAfterBoth2、applyToEither/acceptEither/run…

    2022年6月28日

发表回复

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

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