美文网首页
java反射

java反射

作者: 提拉米苏_cad2 | 来源:发表于2017-09-05 11:32 被阅读0次

    具体代码

    1、实体类

    public classCompute {

    privateStringa;

    publicString getA() {

    return a;

    }

    public voidsetA(String a) {

    this.a= a;

    }

    @Override

    publicString toString() {

    return a;

    }

    }

    2、反射测试

    public static voidmain(String[] args) {

    try{

    //第一种反射的方法

    String classPath ="reflect.Compute";

    Class c1 = Class.forName(classPath);

    Object obj = c1.newInstance();

    String attrName ="a";

    String attrValue ="hello";

    Method method = c1.getMethod("set"+ attrName.toUpperCase(), String.class);

    method.invoke(obj,attrValue);

    System.out.println(obj.toString());

    //第二种反射的方法

    Compute compute =new Compute();

    Method method1 = Compute.class.getMethod("setA",String.class);

    method1.invoke(compute,"liu yuan yuan");

    System.out.println(compute.toString());

    }catch(Exception e) {

    e.printStackTrace();

    }

    }

    反射:

    1)getMethod方法:首先找到实体类中对应的方法setA,String.class是其参数,参数多的时候可以用数组把这些参数装起来。

    2)invoke方法:compute是要改变的具体的实体类,"liu yuan yuan"是其具体参数

    相关文章

      网友评论

          本文标题:java反射

          本文链接:https://www.haomeiwen.com/subject/nxjujxtx.html