zoukankan      html  css  js  c++  java
  • Java 反射的基本应用

    package com.lf.testreflection;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    import org.junit.Test;
    
    public class ClassTest{
        
        @Test
        public void testSomthing()throws Exception {
            //创建运行时类的对象
            Class cla = Person.class;
            // 创建运行时Person的对象
            Person person = (Person)cla.newInstance();
            // 通过cla获取对象的属性
            Field field = cla.getDeclaredField("name");
            // 设置可以访问的权限
            field.setAccessible(true);
            // 设置相应的属性值
            field.set(person, "kity");
            //获取相应的属性(public可以使用下面方法获取)
            field = cla.getField("address");
            field.set(person, "NewYo");
            field = cla.getDeclaredField("age");
            field.setAccessible(true);
            field.set(person, 18);
            
            System.out.println(person);
            // 获取无参方法
            Method method = cla.getMethod("learn");
            method.invoke(person);
            // 获取有参方法
            Method method2 =cla.getMethod("readSomething",String.class);
            method2.invoke(person, "ainsy");
            // 获取多参方法
            Method method3 =cla.getMethod("readSomething",int.class,String.class);
            method3.invoke(person, 20,"ainsy");
            // 获取所有的属性
            Field[] fields = cla.getDeclaredFields();
            for (Field field2 : fields) {
                // 每个属性的修饰符
                System.out.print(field2.getModifiers()+"  ");
                // 每个属性名
                System.out.print(field2.getName()+"  ");
                // 获取属性的类型
                Class type = field2.getType();
                System.out.println(type);
            }    
            
            // 调用运行时本身的.class属性
            Class cla2 = Person.class;
            //打印类路径
            System.out.println(cla2.getName());
            
            // 通过运行时类的对象获取
            Person p = new Person();
            Class cla3 = p.getClass();
            System.out.println(cla3.getName());
        }
    }
  • 相关阅读:
    微信机器人-定制消息
    Python实现微信祝福语自动发送
    日常使用 ADB 命令
    python 中的三种等待方式
    Appium自动化测试之环境安装
    Charles 模拟弱网
    Navicat连接MySQL报错-2059
    requests高级用法
    requests基本用法
    Monkey测试环境搭建
  • 原文地址:https://www.cnblogs.com/lantu1989/p/6097371.html
Copyright © 2011-2022 走看看