欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 反射机制详解及实例代码

程序员文章站 2024-03-11 19:30:01
java 反射机制: 测试实体类 以human为例 /** * project: day12_for_lxy * created: lulu *...

java 反射机制:

测试实体类

以human为例

/**
 * project: day12_for_lxy
 * created: lulu
 * date: 2016/8/10
 */
public class human<t> {
  private string name;
  private int age;
  private float height;

  private static int legs = 2;
  private map<string, string> jobs;
  private t t;

  public int say() {
    system.out.println("i'm" + name);
    return 0;
  }
  private void sleep(human human) {
    system.out.println(name + " sleep with " + human.name);
  }
  public list<integer> getlist() {
    return new arraylist<>();
  }
  public human() {
  }
  private human(string name, int age, float height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    if (age > 150 || age < 0) {
      throw new runtimeexception("age > 150 || age < 0");
    }
    this.age = age;
  }
  public float getheight() {
    return height;
  }
  public void setheight(float height) {
    this.height = height;
  }
  @override
  public string tostring() {
    return "human{" +
        "name='" + name + '\'' +
        ", age=" + age +
        ", height=" + height +
        '}';
  }
}

测试获取构造方法

/**
 * project: day12_for_lxy
 * created: lulu
 * date: 2016/8/10
 */
/*
获取构造方法
 */
public class testconstructor {
  public static void main(string[] args) {
    //得到相应的类结构, 这是用来描述human这个类的类
    class<human> humanclass = human.class;
    try {
////      这是在知道构造方法结构的前提下
//      //获取都明确参数的构造方法, 获取的是公开的(public)
//      constructor<human> constructor1 = humanclass.getconstructor(string.class, integer.type, float.type);
//
//      human h1 = constructor1.newinstance("小明", 18, 1.85f);
//      system.out.println(h1.tostring());
//
//      //构造方法, 修饰符类型
//      int modifiers = constructor1.getmodifiers();
//      if (modifier.ispublic(modifiers)) {
//        system.out.println("是public");
//      }

//      ////获取都明确参数的构造方法, 获取的是声明的
//      constructor<human> constructor2 = humanclass.getdeclaredconstructor(string.class, integer.type, float.type);
//      //设置可以全部访问
//      constructor2.setaccessible(true);
//      //这样是可以获取到所有的构造方法, 包括私有的
//      human human2 = constructor2.newinstance("zll", 18, 1.80f);
//      system.out.println(human2.tostring());

      //不知道构造方法的类结构
      constructor<?>[] constructors = humanclass.getdeclaredconstructors();

      for (constructor<?> c : constructors) {
        c.setaccessible(true);
        system.out.println(c.getname());
        system.out.println("===========================");
        //参数列表
        class<?>[] types = c.getparametertypes();
        for (class<?> type : types) {
          system.out.println(type.gettypename());
        }

        //修饰符类型
        int modifiers = c.getmodifiers();
        if (modifier.ispublic(modifiers)) {
          system.out.println("是公开的");
        }else if (modifier.isprivate(modifiers)){
          system.out.println("是私有的");
        }
      }


    } catch (exception e) {
      e.printstacktrace();
    }

  }
}

测试获取字段

/**
 * project: day12_for_lxy
 * created: lulu
 * date: 2016/8/10
 */

/*
获取属性:
属性包括:( 属性名 类型 修饰符 泛型 )
父类的属性
自身的属性
 */
public class testfield {
  public static void main(string[] args) {
    class<human> humanclass = human.class;
    field[] fields = humanclass.getdeclaredfields();
    for (field f : fields) {

      //属性名
      system.out.print(" 名字: " + f.getname() + " ");
      system.out.println();
      //类型
      system.out.print("类型 :" + f.gettype() + " ");
      system.out.println();
      //修饰符
      int modifiers = f.getmodifiers();
      if (modifier.ispublic(modifiers)) {
        system.out.println("公开的");
      } else if (modifier.isprivate(modifiers)) {
        system.out.println("私有的");
      }
    }
    system.out.println("============================泛型==================================");
    try {
      //通过类结构获取jobs属性
      field jobs = humanclass.getdeclaredfield("jobs");
      //泛型
      parameterizedtype type = (parameterizedtype) jobs.getannotatedtype().gettype();
      type[] types = type.getactualtypearguments();
           for (type type1 : types) {
        system.out.println(type1);
      }
    } catch (exception e) {
      e.printstacktrace();
    }
    system.out.println("===================设置值, 得到值============================");

    try {
      human<object> human = new human<>();
      //非静态, 你要知道给谁设置属性的值
      field namefield = humanclass.getdeclaredfield("name");
      namefield.setaccessible(true);
      namefield.set(human, "路新艺");
      system.out.println(human.getname());

      //静态
      field legs = humanclass.getdeclaredfield("legs");
      int modifiers = legs.getmodifiers();
      legs.setaccessible(true);
      if (modifier.isstatic(modifiers)) {
        system.out.println("是静态的");
      }
      legs.set(null, 4);
      system.out.println(legs.get(null));

    } catch (exception e) {
      e.printstacktrace();
    }
  }
}

测试获取方法

/**
 * project: day12_for_lxy
 * created: lulu
 * date: 2016/8/10
 */
/*
获取方法:
方法名
修饰符
返回值类型
泛型

静态和非静态

方法的调用

 */
public class testmethod {
  public static void main(string[] args) {

    class<human> humanclass = human.class;
    //方法名
    method[] ms = humanclass.getdeclaredmethods();
    for (method m : ms) {
      m.setaccessible(true);
      system.out.print("方法名: " + m.getname() + "  " );
      int modifiers = m.getmodifiers();

      if (modifier.ispublic(modifiers)) {
        system.out.println("公开的");
      } else if (modifier.isprivate(modifiers)) {
        system.out.println("私有的");
      }
    }
    //在确定方法参数的情况下  方法名不能唯一的确定, 重载
    try {
      //普通类型
      method saym = humanclass.getdeclaredmethod("say");
      class<?> returntype = saym.getreturntype();
      system.out.println(returntype.tostring());
      //泛型
      method getlistm = humanclass.getdeclaredmethod("getlist");
      system.out.println(getlistm.getreturntype());

      parameterizedtype type = (parameterizedtype) getlistm.getannotatedreturntype().gettype();
      system.out.println(type);
      type[] ts = type.getactualtypearguments();
      for (type t : ts) {
        system.out.println(t);
      }


    } catch (exception e) {
      e.printstacktrace();
    }
  }
}

测试获取类信息

public static void main(string[] args) {
  printclassinfo(student.class);
}

public static void printclassinfo(class c){
    //java中唯一的父类的类时object
    system.out.println(c.getname());
    system.out.println(c.getsimplename());
    system.out.println(c.getsuperclass());

    class[] interfaces = c.getinterfaces();
    for (class aninterface : interfaces) {
      system.out.println(aninterface);
    }
    //外部类类只有两种访问权限修饰(public 和 default)
    int modifiers = c.getmodifiers();
  }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!