反射入门_入门教程

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


相关推荐

  • 稳压管稳压电路

    稳压管稳压电路一、稳压管稳压电路:整流滤波电路的输出电压会随着电网电压的波动而波动,随着负载电阻的变化而变化。为了获得稳定性好的直流电压,必须采取稳压措施。二、稳压原理:对于任何稳压电路而言,都应该从两方面来考虑:电网电压波动、负载变化,研究其输出电压是否稳定。(1)、电网电压波动:(2)、负载变化:…

    2022年6月20日
    22
  • Win10运行PS很卡,分享几种解决Win10用PS卡顿提速设置方法

    Win10运行PS很卡,分享几种解决Win10用PS卡顿提速设置方法转载自品略图书馆http://www.pinlue.com/article/2020/04/0117/3410102560823.html最近升级了Win10系统,安装了PS软件准备工作,但是命使用中发现PS很卡,卡顿问题比较明显,极度的影响使用,那么如何解决呢?下面小编整理了解决方法,相信通过以下的设置之后,PS卡顿问题可以解决。与自定义配置是有很大关系的。特别是一些新功能的加入,在一些低配置电脑上往往会有事倍功半的“奇效”。如果你的PS用起来很卡,不妨赶快检查以下几个选项,可以瞬间提速1..

    2022年5月7日
    100
  • 机器学习–组合分类方法之随机森林算法原理和实现(RF)

    上一节我们详细的介绍了组合分类方法中的boosting提升算法中经典的adaboost提升算法,当然还有其他的提升算法例如:前向分步算法(adaboost算法是该算法的一个特殊情况,)、提升树算法(基于加法模型和前向分布算法),其中提升树的学习算法即损失函数有:平方误差损失函数、指数损失函数、梯度损失函数等在这里就不细讲他们了,因为他们的算法思想都是基于boost提升的,只是学习算法不同罢了,有兴…

    2022年4月9日
    45
  • pycharm2021 5.2激活码破解方法

    pycharm2021 5.2激活码破解方法,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月15日
    37
  • UE4导入高度图

    UE4导入高度图UE4导入高度图查找高度图使用ps编辑图片打开虚幻引擎的地形编辑器查找高度图可以从百度直接搜索使用ps编辑图片下载下来之后图片是jpg格式的,虚幻引擎不能直接用需要使用ps编辑一下选择图像->勾选灰度和16位通道,注意:如果不勾选灰度,图片有颜色的话,ue生成地形可能出现为题;还有ue只支持16位通道,不要选择其他通道点击文件和储存为,之后出现一个弹窗,填写自己图片的名字,注意图片的格式只能是png和raw,其他格式ue不支持打开虚幻引擎的地形编辑器1.ue4.25的地形在模式

    2022年5月26日
    49
  • 精灵图 详解

    精灵图 详解精灵图技术why?1.减少请求次数,提高界面加载速度what?图片拼合技术,它就是把多张小图合成一张大图,利用 背景定位属性background-position:xpxypx实现显示大图当中的某一个小图how?1.确定显示小图片的那个盒子的宽高2.以背景的方式插入精灵图background-image:url();3.移动图片的定位位置background-positi…

    2022年5月6日
    52

发表回复

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

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