• java反射专题三


    一丶调用运行时类中指定的属性

           Class clazz = Person.class;
           //1.获取指定的属性
           Field name = clazz.getField("name");//获取运行时类及其父类中声明public的指定名为name的属性
           //2.创建运行时类的对象
           Person person = (Person) clazz.newInstance();
           //3.将运行时类的指定属性赋值
           name.set(person, "Jerry");
           Field age = clazz.getDeclaredField("age");//可以获取运行时类中指定名为age的属性
           age.setAccessible(true);//由于属性权限修饰符的限制,为了保证可以给属性赋值,需要在设置属性前使得有权限操作该属性
           age.set(person, 11);

    二丶调用运行时类中指定的方法

           Class clazz = Person.class;
           //1.获取运行时类中声明public的指定的方法
           Method method = clazz.getMethod("display", String.class);//有一个String类型的形参,第二个参数是变长参数,如果没有形参就不写
           Person person = (Person) clazz.newInstance();
           Object returnVal = method.invoke(person, "hello");//返回值就对应到具体调用方法的返回值
           //2.获取运行时类中指定的方法
           Method m = clazz.getDeclaredMethod("show");
           m.setAccessible(true);//和属性一个意思
           m.invoke(person);
           //3.获得静态的方法
           Method m3 = clazz.getMethod("info");
           m3.invoke(Person.class);//对于静态方法的掉用

     三丶调用指定的构造器

           Class clazz = Person.class;
           //获取运行时类中指定的构造器
           Constructor c = clazz.getDeclaredConstructor(String.class,int.class);
           c.setAccessible(true);
           Person p = (Person)c.newInstance("Tom",20);//通过指定构造器创建对象
  • 相关阅读:
    查看Ubuntu操作系统位数 Anny
    no such file to load zlib when using gem install Anny
    Error: shasum check failed for /tmp/npm1316662414557/13166624159930.13772299513220787/tmp.tgz Anny
    Future接口的应用
    ScheduledThreadPool
    弄了个群
    阻塞与中断
    获得CPU个数
    文件路径问题
    一个日志服务器的框架
  • 原文地址:https://www.cnblogs.com/cainiao-Shun666/p/8568763.html
Copyright © 2020-2023  润新知