1
0
mirror of https://github.com/Snailclimb/JavaGuide synced 2025-06-16 18:10:13 +08:00

fix typo: taget -> target in reflection.md

Signed-off-by: sam <sam2008ext@gmail.com>
This commit is contained in:
sam 2022-02-22 03:44:30 +08:00
parent 13b950686d
commit e2b84376fc

View File

@ -130,33 +130,33 @@ public class Main {
/** /**
* 获取TargetObject类的Class对象并且创建TargetObject类实例 * 获取TargetObject类的Class对象并且创建TargetObject类实例
*/ */
Class<?> tagetClass = Class.forName("cn.javaguide.TargetObject"); Class<?> targetClass = Class.forName("cn.javaguide.TargetObject");
TargetObject targetObject = (TargetObject) tagetClass.newInstance(); TargetObject targetObject = (TargetObject) targetClass.newInstance();
/** /**
* 获取所有类中所有定义的方法 * 获取所有类中所有定义的方法
*/ */
Method[] methods = tagetClass.getDeclaredMethods(); Method[] methods = targetClass.getDeclaredMethods();
for (Method method : methods) { for (Method method : methods) {
System.out.println(method.getName()); System.out.println(method.getName());
} }
/** /**
* 获取指定方法并调用 * 获取指定方法并调用
*/ */
Method publicMethod = tagetClass.getDeclaredMethod("publicMethod", Method publicMethod = targetClass.getDeclaredMethod("publicMethod",
String.class); String.class);
publicMethod.invoke(targetObject, "JavaGuide"); publicMethod.invoke(targetObject, "JavaGuide");
/** /**
* 获取指定参数并对参数进行修改 * 获取指定参数并对参数进行修改
*/ */
Field field = tagetClass.getDeclaredField("value"); Field field = targetClass.getDeclaredField("value");
//为了对类中的参数进行修改我们取消安全检查 //为了对类中的参数进行修改我们取消安全检查
field.setAccessible(true); field.setAccessible(true);
field.set(targetObject, "JavaGuide"); field.set(targetObject, "JavaGuide");
/** /**
* 调用 private 方法 * 调用 private 方法
*/ */
Method privateMethod = tagetClass.getDeclaredMethod("privateMethod"); Method privateMethod = targetClass.getDeclaredMethod("privateMethod");
//为了调用private方法我们取消安全检查 //为了调用private方法我们取消安全检查
privateMethod.setAccessible(true); privateMethod.setAccessible(true);
privateMethod.invoke(targetObject); privateMethod.invoke(targetObject);
@ -177,6 +177,6 @@ value is JavaGuide
**注意** : 有读者提到上面代码运行会抛出 `ClassNotFoundException` 异常,具体原因是你没有下面把这段代码的包名替换成自己创建的 `TargetObject` 所在的包 。 **注意** : 有读者提到上面代码运行会抛出 `ClassNotFoundException` 异常,具体原因是你没有下面把这段代码的包名替换成自己创建的 `TargetObject` 所在的包 。
```java ```java
Class<?> tagetClass = Class.forName("cn.javaguide.TargetObject"); Class<?> targetClass = Class.forName("cn.javaguide.TargetObject");
``` ```