Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions docs/java/basis/reflection.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,36 +132,35 @@ 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());
}

/**
* 获取指定方法并调用
*/
Method publicMethod = tagetClass.getDeclaredMethod("publicMethod",
Method publicMethod = targetClass.getDeclaredMethod("publicMethod",
String.class);

publicMethod.invoke(targetObject, "JavaGuide");

/**
* 获取指定参数并对参数进行修改
*/
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);
}
Expand All @@ -181,6 +180,6 @@ value is JavaGuide
**注意** : 有读者提到上面代码运行会抛出 `ClassNotFoundException` 异常,具体原因是你没有下面把这段代码的包名替换成自己创建的 `TargetObject` 所在的包 。

```java
Class<?> tagetClass = Class.forName("cn.javaguide.TargetObject");
Class<?> targetClass = Class.forName("cn.javaguide.TargetObject");
```