1
0
mirror of https://github.com/Snailclimb/JavaGuide synced 2025-06-20 22:17:09 +08:00

Merge pull request #1560 from samho2008/fix-typo-reflection

fix typo: taget -> target in reflection.md
This commit is contained in:
Guide哥 2022-02-22 21:36:48 +08:00 committed by GitHub
commit 4789216e61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

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