当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java通过反射调用对象的方法
发布时间:2010/5/14 11:25:21 来源:城市学习网 编辑:ziteng
  TestRef.java
  import java.lang.reflect.Method;
  import java.lang.reflect.InvocationTargetException;
  /**
  * Created by IntelliJ IDEA.
  * File: TestRef.java
  * User: String
  * Date: 2010-3-29 14:48:44
  */
  public class TestRef {
  public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  Foo foo = new Foo("这个一个Foo对象!");
  Class clazz = foo.getClass();
  Method m1 = clazz.getDeclaredMethod("outInfo");
  Method m2 = clazz.getDeclaredMethod("setMsg", String.class);
  Method m3 = clazz.getDeclaredMethod("getMsg");
  m1.invoke(foo);
  m2.invoke(foo, "重新设置msg信息!");
  String msg = (String) m3.invoke(foo);
  System.out.println(msg);
  }
  }
  class Foo {
  private String msg;
  public Foo(String msg) {
  this.msg = msg;
  }
  public void setMsg(String msg) {
  this.msg = msg;
  }
  public String getMsg() {
  return msg;
  }
  public void outInfo() {
  System.out.println("这是测试Java反射的测试类");
  }
  }
  控制台输出结果:
  这是测试Java反射的测试类
  重新设置msg信息!
  Process finished with exit code 0
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved