首先我们获得一个类对象有三种方法
1:Student.class
2:new Student().getClass();
3:Class.forName(报名+类名);
下面是我实验的例子
ReflectBasicStudy:测试类
Student:被操作类 (在文章末尾查看)
通过测试方法 来对 ReflectBasicStudy 中的方法进行测试,控制台打印日志观察
基础用法:
调用构造方法
调用成员方法
获取字段
1:调用构造方法:
调用无参构造方法
/* 获取类 */
clazz = Class.forName(studentPackage);
constructor = clazz.getConstructor();
/* 获取类的实例 */
student = constructor.newInstance();
调用有参私有构造方法
constructor1 = clazz.getDeclaredConstructor(String.class, int.class);//这里需要指定构造方法各个参数的类型
/* 并且设置 setAccessible 值为 true 否则会报错 NoSuchMethodException */
constructor1.setAccessible(true);
student1 = constructor1.newInstance("边先生", 28);//这里对应上方传递对应类型参数
这里 getDeclaredConstructor 和 getConstructor 区别为:
getConstructor只能获取公有
getDeclaredConstructor 可获取:getDeclaredConstructor
后面不在做相关注释;
获取所有构造方法
Constructor[] conArr = clazz.getDeclaredConstructors();
for (Constructor c : conArr) {
System.out.print(c + "\n");
}
2:调用成员方法
获取所有成员方法
Method[] methodArr = clazz.getDeclaredMethods();
/* 打印出来 */
for (Method method : methodArr) {
System.out.print(method + "\n");
}
调用有返回值方法
Method getNameMethod = clazz.getDeclaredMethod("getName");//这里共有私有解释以上放相同不做解释,后面都用类似方法;
getNameMethod.setAccessible(true);
Object nameObj = getNameMethod.invoke(student1);//这里传入操作的实例
调用传参方法
Method setNameAndAgeMethod = clazz.getDeclaredMethod("setNameAndAge", String.class, int.class);//传入方法名,及各参数类型
setNameAndAgeMethod.setAccessible(true);
/* 执行方法 */
setNameAndAgeMethod.invoke(student1, "皮卡丘", 3);//传入操做的实例及对应的各参数
3:调用成员变量
获取所有字段
Field[] fieldArr = clazz.getDeclaredFields();
for (Field f : fieldArr) {
System.out.print(f + "\n");
}
获取字段并赋值
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
/* 先打印 name 的值 */
System.out.print("name_before:" + clazz.getMethod("getName").invoke(student1) + "\n");
field.set(student1, "王力宏");
/* 在打印 name 的值 */
System.out.print("name_after:" + clazz.getMethod("getName").invoke(student1) + "\n");
参考文章:
https://blog.csdn.net/u010648159/article/details/79673655
https://blog.csdn.net/lwl20140904/article/details/80163880
很晚了,下一篇在好好排版吧(其实我还不会排版。。)。幸运能被大大您看到非常感谢!!请见谅
代码下载链接: