mirror of
https://github.com/Snailclimb/JavaGuide
synced 2025-06-16 18:10:13 +08:00
improve reflection.md: add white space and line feed
This commit is contained in:
parent
13b950686d
commit
370a6d616c
@ -71,7 +71,7 @@ Class alunbarClass = TargetObject.class;
|
||||
|
||||
但是我们一般是不知道具体类的,基本都是通过遍历包下面的类来获取 Class 对象,通过此方式获取 Class 对象不会进行初始化
|
||||
|
||||
**2.通过 `Class.forName()`传入类的路径获取:**
|
||||
**2. 通过 `Class.forName()`传入类的全路径获取:**
|
||||
|
||||
```java
|
||||
Class alunbarClass1 = Class.forName("cn.javaguide.TargetObject");
|
||||
@ -90,7 +90,7 @@ Class alunbarClass2 = o.getClass();
|
||||
Class clazz = ClassLoader.loadClass("cn.javaguide.TargetObject");
|
||||
```
|
||||
|
||||
通过类加载器获取 Class 对象不会进行初始化,意味着不进行包括初始化等一系列步骤,静态块和静态对象不会得到执行
|
||||
通过类加载器获取 Class 对象不会进行初始化,意味着不进行包括初始化等一系列步骤,静态代码块和静态对象不会得到执行
|
||||
|
||||
### 反射的一些基本操作
|
||||
|
||||
@ -132,13 +132,15 @@ public class Main {
|
||||
*/
|
||||
Class<?> tagetClass = Class.forName("cn.javaguide.TargetObject");
|
||||
TargetObject targetObject = (TargetObject) tagetClass.newInstance();
|
||||
|
||||
/**
|
||||
* 获取所有类中所有定义的方法
|
||||
* 获取 TargetObject 类中定义的所有方法
|
||||
*/
|
||||
Method[] methods = tagetClass.getDeclaredMethods();
|
||||
for (Method method : methods) {
|
||||
System.out.println(method.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定方法并调用
|
||||
*/
|
||||
@ -146,18 +148,20 @@ public class Main {
|
||||
String.class);
|
||||
|
||||
publicMethod.invoke(targetObject, "JavaGuide");
|
||||
|
||||
/**
|
||||
* 获取指定参数并对参数进行修改
|
||||
*/
|
||||
Field field = tagetClass.getDeclaredField("value");
|
||||
//为了对类中的参数进行修改我们取消安全检查
|
||||
// 为了修改类中的私有字段我们必须取消安全检查
|
||||
field.setAccessible(true);
|
||||
field.set(targetObject, "JavaGuide");
|
||||
|
||||
/**
|
||||
* 调用 private 方法
|
||||
*/
|
||||
Method privateMethod = tagetClass.getDeclaredMethod("privateMethod");
|
||||
//为了调用private方法我们取消安全检查
|
||||
// 为了调用 private 方法我们必须取消安全检查
|
||||
privateMethod.setAccessible(true);
|
||||
privateMethod.invoke(targetObject);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user