• Java relection half


    //原类

    package mypackage;

    public class forclass {
     public static String name="xiaoMing";
     public static int     age=12;
     
     public  void  prinfMethod()
     {
      System.out.println("gaowh  print");
     }
    }

    //普通方法实例化

    package mypackage;

    public class commonInvork {


     public static void main(String[] args) {

      forclass my=new forclass();
      my.prinfMethod();
     }

    }

    //For class invoke

    package mypackage;

    import java.lang.reflect.Field;

    public class forClassInvoke{
     
     public static void main(String args[]) throws Exception{
    //    Class<?> my=Class.forName("mypackage.forclass");
     // newInstance of reflected class, then invoke the method of the reflected class
      //this method can print all static and non static constants or methods
    //    forclass newobject=(forclass)my.newInstance();
    //    newobject.prinfMethod();
    //    System.out.println(newobject.age);
    //   

       Class ownerClass = Class.forName("mypackage.forclass");  
       //Field[] fields= ownerClass.getDeclaredFields(), it is used to get
       //all public and private constants ,but getFields is used to get only punlic constants
       Field[] fields= ownerClass.getFields();
       for(int i=0;i<fields.length;i++)
       {   
        //find the filedname and field type
        System.out.println("zz="+fields[i].getName()+"==>"+fields[i].getType()); 
       }  
       //get the value of the static field
          Field field = ownerClass.getField("name");           
          Object value = field.get(ownerClass);  
          //print value
          System.out.println(value);

     }
    }

  • 相关阅读:
    Linux磁盘与文件系统操作命令
    Linux 进程管理命令
    文件备份与压缩命令
    Linux系统命令
    CentOS6和CentOS7的区别
    nginx安装配置
    docker的容器和镜像的清理
    Zabbix-Agent配置文件详解
    k8s 获取登录token命令
    vmware 端口转发设置
  • 原文地址:https://www.cnblogs.com/halfacre/p/3105240.html
Copyright © 2020-2023  润新知