加载类:
1 类名.class,
2 对象.getClass()
3 Class.forName(“类名”)
tips
1 int.class是一个class类型的对象
2 if(e.getclass()==Employee.class)
3 e.getClass().newInstance();//只能调用默认的没有参数的构造器
getConstructors(),getField(),getMethod():返回类中的public构造器函数,域和方法(包括超类中)
getDeclaredConstructors(),getDeclaredField(),getDeclaredMethod():返回所有的构造器函数,域和方法(不包括超类中)
public int getModifiers()
public
, protected
, private
, final
, static
, abstract
and interface
; they should be decoded using the methods of class Modifier
.在运行时使用反射分析对象:
1 使用Field对象的get(对象)方法可以得到对象的域值,用set(对象,参数)可以设置域值。
如果为private域,需要调用setAccessible(true)方法
getType()得到域的类型
2 使用Constructor对象可以创建对象(得到不同参数的构造器getConstructor(Class1,Class2....),再传入相应的参数构造对象newInstance(参数1,参数2....))。
如果为private构造函数,需要调用setAccessible(true)方法
3 反射类的方法,并且调用(invoke(obj,参数...))
如果是private方法,需要调用setAccessible(true)方法
如果是静态方法,则不需要传入对象
如果是main方法 :
method.invoke(null, new Object[]{new String[]{"a","b"}});
//method.invoke(null, (Object)new String[]{"a","b"});