zoukankan      html  css  js  c++  java
  • 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);//通过指定构造器创建对象
  • 相关阅读:
    穷举字符串的一种算法
    使用VirtualBox SDK之初步编译
    Install Shield 中判断安装还是卸载
    [转] win32内核程序中进程的pid,handle,eprocess之间相互转换的方法
    如何做PHD (1)
    在TFS 2010中使用邮件提醒功能(Email Notification)
    Chrome的Awesome Screenshot的插件离线下载
    Visual Studio 2010下生成Crypto++ lib
    VirtualBox开发环境的搭建详解
    VC版PwdHash
  • 原文地址:https://www.cnblogs.com/cainiao-Shun666/p/8568763.html
Copyright © 2011-2022 走看看