一、Class类
- 在面对对象编程中,万事万物皆对象,但是类本身又是谁的对象呢? 他是java.lang.Class的对象
- 获取类类型的3种方法
- 通过对象类的对象获取
Foo foo = new Foo();
Class class1 = foo.getClass();
- 通过类名获取
Class class2 = Foo.class;
- 还是通过类名获取,但是要try catch, 并且要转换类型
try {
Class class3 = (Class) Class.forName("Foo")
二、获取类的方法信息
- 一个成员方法就是Method类的对象
- getMethods()是获得该类的所有public方法,包括从父类继承来的方法
Method[] methods1 = class1.getMethods();
- getDeclaredMethods()是获取当前类自己声明的成员方法,不包含父类继承来的,但是不问访问权限
Method[] methods2 = class1.getDeclaredMethods();
- 得到返回值类型,先得到返回值类型的类类型,再获得名字
Class returnType = methods1[i].getReturnType();
String returnTypeName = returnType.getName();
for (int i = 0; i < methods1.length; i++) {
System.out.println(methods1[i].getName());
}
- 得到参数类型,因为参数可能有多个,所以先得到参数列表,再遍历它得到参数类型的名字
Class[] paramTypes = methods1[i].getParameterTypes();
for (Class paramType : paramTypes) {
String paramTypeName = paramType.getName();
}
三、获取成员变量的信息
- 成员变量是java.lang.reflect.Field类的对象
- getFields()获得的是所有public的成员变量
Field[] fields1 = class1.getFields()
- getDeclaredFields()获得的是自己声明的所有的成员变量
Field[] fields2 = class1.getDeclaredFields()
for (Field field : fields2) {
Class fieldType = field.getType();
String fieldTypeName = fieldType.getName();
}
String fieldName = field.getName()
四、获取构造函数的信息
- 构造函数是java.lang.reflect.Constructor的对象
- 获得构造函数,方法基本同上
Constructor[] constructors1 = class1.getConstructors();
Constructor[] constructors2 = class1.getDeclaredConstructors();
for (Constructor constructor : constructors2)
String csName = constructor.getName();
五、 反射调用方法
public class A {
public void print(int a, int b) {
System.out.println(a + b);
}
public void print(String a, String b) {
System.out.println(a.toUpperCase() + b.toLowerCase());
}
}
A a1 = new A();
Class clazz = a1.getClass();
六、通过反射操作绕过编译,以集合泛型为例
public class MethodDemo1 {
public static void main(String[] args) {
ArrayList list1 = new ArrayList();
ArrayList<String> list2 = new ArrayList<String>();
Class c1 = list1.getClass();
Class c2 = list2.getClass();