A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© stormdzh 中级黑马   /  2013-7-13 18:51  /  963 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

求给个反射的简单实例!

2 个回复

倒序浏览
  1. import java.lang.reflect.*;
  2. class loadclass
  3. public class reflecttest {
  4. static
  5. {
  6. System.out.PRintln("Class reflecttest loaded");
  7. }
  8. public static void staicMethod()
  9. {
  10. System.out.println("staticMethod Called");
  11. }
  12. public void instanceMethod()
  13. {
  14. System.out.println("instanceMethod Called");
  15. }
  16. public static void main(String[] args) {
  17. Class c=reflecttest.class;
  18. try {
  19. Method method = c.getMethod("staicMethod", null);
  20. method.invoke(c,null);
  21. method.invoke(c.newInstance(),null);

  22. method=c.getMethod("instanceMethod",null);
  23. //method.invoke(c,null);
  24. //将抛出异常IllegalArgumentException:object is not an instance of declar
  25. ing class
  26. method.invoke(c.newInstance(),null);
  27. }
  28. catch (Exception ex) {
  29. ex.printStackTrace();
  30. }
  31. }
  32. }
复制代码
回复 使用道具 举报 1 0
//被下面反射调用的方法
   public void show(){
           System.out.println("被反射调用");
   }
   //临时写个反射的简单是咧
   public void reflectShow(){
           //1.获取本类字节码对象myTestclass
           Class myTestClass=this.getClass();
           try {
                   //2.获取字节码对象的show 参数null可以不写
                   Method show=myTestClass.getMethod("show");
                   //3.执行show方法对象参数null可以不写
                   show.invoke(this);//this表示被反射的类的实例
        } catch (Exception e) {
                e.printStackTrace();
        }
   }
回复 使用道具 举报 1 0
您需要登录后才可以回帖 登录 | 加入黑马