现在的位置: 首页 > 综合 > 正文

梦入IBM之java基础第十四天反射

2014年02月01日 ⁄ 综合 ⁄ 共 795字 ⁄ 字号 评论关闭

十四天了,今天我们来谈谈反射吧:

反射就是通过class对象来获得类加载时候的一些基本信息!类的成员变量和方法!

1):获得class对象的方法:三种:1): Class类的 静态forName方法,记得加包名!

                                                                 2):类名.class

                                                                 3):剑柄.getClass()方法

2):通过class对象获得构造方法,然后再调用!

           用Constructor  cons  = classType.getConstructor(new Class[]{});得到对象

           然后再调用:Object obj = cons.newInstance(new Object[]{});.

3):通过class对象获得方法,然后再调用!

           Method method = classType.getDeclaredMethod("toString", new Class[]{});得到对象

           再调用:method.invoke(s, new Object[]{});

4):通过class对象得到属性:

          Field field = classType.getDeclaredField("jint");

5):通过class对象得到注解

          Annotation ao = method.getAnnotation(注解名.class)

          (常用)Method method = cllassType.getMethod(......)

          if(method.isAnnotionPresent(Before.class))

          {

             执行业务逻辑! 

          }

思维导图:

         Annotation[]  an = classType.getAnnotations();

抱歉!评论已关闭.