反射/内省

反射:

类的加载器将class文件加载到jvm中,那么有一个Class对象(代表是class文件加载到内存后所形成的一个对象)
第一步获得代表这个类加载到内存的字节码文件的对象Class对象
  三种方式:
    1.通过类名.class
    2.通过类的实例对象.getClass();
    3.通过Class的forName()的静态方法(推荐使用)
万物皆对象,在反射中类的构造器,成员变量及方法都是对象:
  Construcotr:构造器对象
  Field:属性对象
  Method:方法对象
通过反射操作构造方法&属性对象&方法对象:
Class AIP:
  T newInstance():创建此Class对象所表示的类的新实例。(采用默认的无参构造)
  Constructor<T> getConstructor(Class<?>... parameterTypes):返回指定参数列表的public构造器
  Field getField(String name):返回指定public字段的Field对象。
  Field[] getFields():返回所有的public字段对象。
  Field getDeclaredField(String name):返回指定字段的field对象,私有对象亦可返回
  Method getMethod(String name,Class<?> parameterType):返回一个名称为name的public的Method对象
  Method getDeclaredMethod(String name,Class<?> parameterType):返回ige名称为name的Method对象,私有亦可获得
Constructor AIP:
  T newInstance(Object... initargs):使用此Constructor表示的构造方法创建该构造方法的声明类的新实例
Field AIP:
  void setAccessible(boolean flag):设置为true表示该Field字段可以修改。
  Object get(Object obj)//返回指定对象上此字段的值
  void set(Object obj,Object value)//将指定对象上此字段的值设置为value
Method API:
  void setAccessible(boolean flag):设置为true表示该method方法不论公私都可以执行。
  Object invoke(Object obj,Object...args):执行obj对象的该method方法

内省:

  内省是得到javabean的属性及属性的get或set方法;
javabean就是一个满足了特定格式的java类;
  1.需要提供无参数的构造方法
  2.属性私有
  3.对私有属性提供public的get/set方法

Introspector API:
  static BeanInfo getBeanInfo(Class<?> beanClass):获得javabean的信息
BeanInfo API:
  PropertyDescriptor[] getPropertyDescriptors():获得javabean的属性描述
PropertyDescriptor API:
  String getName() 获得属性名称//这个属性名是由get方法决定的。
  Method getReadMethod() 获得getter方法
  Method getWriteMethod()获得setter方法

使用内省自定义一个MyBeanUtils对参数进行封装到javabean中。

 1 public class MyBeanUtils {
 2 
 3     public static void populate(Object obj,Map<String,String[]> map) throws Exception{
 4         // 获得类的所有的属性的名称:
 5         BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
 6         // 获得类中所有的属性:
 7         PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
 8         for (PropertyDescriptor pd : pds) {
 9             if(map.containsKey(pd.getName())){
10             Method method = pd.getWriteMethod();
11         // 执行set方法:
12         method.invoke(obj, map.get(pd.getName())[0]);
13             }
14         }
15     }
16 }    
原文地址:https://www.cnblogs.com/laodang/p/9464942.html