反射

一.获取运行时类的完整结构

1.

/*
getFields():获取当前运行时类及其父类中声明为public访问权限的属性
getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性)
getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
getDeclaredFields():获取当前运行时类中声明的所有方法(不包含父类中声明的方法
getConstructors():获取前运行时类中声明为public的构造器
getDeclaredConstructors():获取当前运行时类中声明的所有构造器
 */ 

2.获取运行时类属性权限修饰符,数据类型,变量名的方法

3.获取运行时类方法的注解,权限修饰符,返回值类型,方法名的方法

4.获取运行时类方法的形参列表方法

5.获取运行时类方法的异常的方法

6.获取运行时类的构造器

二,调用运行时类的指定结构

1.如何操作运行时类中指定的属性(要求掌握)

2.如何操作运行时类中指定的方法(要求掌握)

3.调用运行时类的指定构造器(运用较少,一般使用clazz.newInstance)

三.代码部分

1.造一个person类

public class Person {
    private String name;

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

    public int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    private Person(String name) {
        this.name = name;

    }

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

2.反射之前和反射之后对person的操作

@Test
    public void test1(){
        //反射之前,对于Person的操作
        //1.创建person类的对象
        Person p1=new Person("tom",12);
        //2.通过对象,调用其内部的属性方法
        p1.age=10;
        System.out.println(p1.toString());
        p1.show();
        //在Person类外部,不可以通过person类的对象调用其内部私有结构
        //比如:name,showNation()以及私有的构造器
    }
    @Test
    //反射之后,对于Person的操作
    public void test2() throws Exception{
        Class clazz = Person.class;
        //1.通过反射创建person类的对象
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        Object obj = constructor.newInstance("tom", 12);
        Person p=(Person) obj;
        System.out.println(p.toString());
        //2.通过反射,调用对象指定的属性,方法
        //调用属性
        Field declaredFields = clazz.getDeclaredField("age");
        declaredFields.set(p,10);
        System.out.println(p.toString());
        //调用方法
        Method show = clazz.getDeclaredMethod("show");
        show.invoke(p);



        //通过反射,可以调用Person类的私有结构的。比如私有的构造器,方法属性
        //调用私有的构造器
        Constructor constructor1 = clazz.getDeclaredConstructor(String.class);
        constructor1.setAccessible(true);
        Object obj1 = constructor1.newInstance("tom1");
        Person p1=(Person) obj1;
        System.out.println(p1.toString());
        //调用私有的属性
        Field field = clazz.getDeclaredField("name");
        field.setAccessible(true);
        field.set(p1,"hanmeimei");
        System.out.println(p1);
        //调用私有的放法
        Method method = clazz.getDeclaredMethod("showNation", String.class);
        method.setAccessible(true);
        String nation= (String) method.invoke(p1,"中国");//相当于p1.showNation("中国")
        System.out.println(nation);
        //疑问:通过直接new的方式或反射 的方式都可以调用公共的结构,开发中到底用哪个?
        //建议:直接new的方式
        //什么时候会用反射:反射的特征:动态性
        //疑问:反射机制与面向对象中的封装性是不是矛盾的?如何看待两个技术
        //不矛盾
        /*
        关于java.lang.Class类的理解
        1.类的加载过程:
        程序经过javac.exe命令以后,会生成一个或多个字节码文件(.class结尾)
        接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件
        加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此
        运行时类,就作为Class的一个实例
        2.换句话说,Class的实例就对应着一个运行时类
        3.加载到内存中的运行时类,会缓存一定的时间。在此时间内,我们可以通过不同的方式来获取此运行时类
         */
    }

3.获取Class的实例的方式(前三种需要掌握)

public void test3() throws ClassNotFoundException {
        //方式一:调用运行时类的属性:.class
        Class clazz = Person.class;
        System.out.println(clazz);
        //方式二:通过运行时类的对象,调用getclass()
        Person p1=new Person();
        Class clazz1 = p1.getClass();
        System.out.println(clazz1);
        //方式三:调用Class的静态方法:forName(String classPath)
        Class clazz2 = Class.forName("com.shanggong.exxer.Person");
        System.out.println(clazz2);
        //方式四:使用类的加载器:ClassLoader(了解)
        ClassLoader classLoader = ReflectionTest.class.getClassLoader();
        Class clazz3 = classLoader.loadClass("com.shanggong.exxer.Person");
        System.out.println(clazz3);
    }

4.Class实例可以是哪些结构的说明:

public void test4(){
        Class c1 = Object.class;
        Class c2 = Comparable.class;
        Class c3 = String[].class;
        Class c4 = int[][].class;
        Class c5 = ElementType.class;
        Class c6 = Override.class;
        Class c7 = int.class;
        Class c8 = void.class;
        Class c9 = Class.class;
        int[] a=new int[10];
        int[] b=new int[100];
        Class c10 = a.getClass();
        Class c11 = b.getClass();
        //只要数组的元素类型与维度一样,就是同一个Class
        System.out.println(c10==c11);
    }

5.Properties配置文件

public class ClassloaderTets {
    @Test
    public void test() throws IOException {
        Properties pro = new Properties();
        //此时的文件默认在当前的module下
        //读取配置文件的方式一
        FileInputStream file=new FileInputStream("jdbc.properties");
        pro.load(file);
        //读取配置文件的方式二:使用Classloader
        //配置文件默认识别为:当前module的src下
        ClassLoader c = ClassloaderTets.class.getClassLoader();
        InputStream resourceAsStream = c.getResourceAsStream("jdbc1.properties");
        pro.load(resourceAsStream);
    }
}

6.体会反射的动态性

public class NewInstanceTest {
    //通过反射创建对应运行时类的对象
    @Test
    public void test() throws IllegalAccessException, InstantiationException {
        Class<Person> clazz = Person.class;
        /*
        newInstance():调用此方法,创建对应的运行时类的对象,内部调用了运行时类的空参构造器、
        要想此方法正常的创建运行时类的对象,要求:
        1.运行时类必须提供空参构造器
        2.空参的构造器的访问权限得够,通常设置为public
       在javabean中要求提供一个public的空参构造器。原因:
       1.便于通过反射,创建运行时类的对象
       2.便于子类继承此运行时类时,默认调用super(),保证父类有此构造器
         */
        Person person = clazz.newInstance();
        System.out.println(person);
    }
    //体会反射的动态性
    @Test
    public void test1(){
        for (int i = 0; i < 10; i++) {
            int num = new Random().nextInt(3);//随机返回0,1,2
            String classpath="";
            switch (num)
            {
                case 0: classpath="java.util.Date";
                    break;
                case 1:classpath="java.lang.Object";
                    break;
                case 2:classpath="com.shanggong.exxer.Person";
                    break;
            }
            try {
                Object  instance = getInstance(classpath);
                System.out.println(instance);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public Object getInstance(String classPath) throws Exception {
        Class clazz = Class.forName(classPath);
        return clazz.newInstance();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值