Skip to content

Commit 7910447

Browse files
committed
add
Signed-off-by: maskleo <[email protected]>
1 parent 1a1440e commit 7910447

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

ch07/05_Reflection_for_Generics.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
## 泛型的反思
2+
3+
泛型以两种方式改变反射库。 我们已经讨论了反射的泛型,其中 `Java` 为类 `Class<T>` 添加了一个类型参数。 我们现在讨论泛型的反射,其中 `Java`添加了支持访问泛型类型的方法和类。
4+
5+
`7-2` 显示了泛型使用反射的简单演示。 它使用反射来查找与给定名称关联的类,并使用反射库类 `Field``Constructor``Method`打印出与该类关联的字段,构造函数和方法。 两种不同的方法可用于将字段,构造函数或方法转换为用于打印的字符串:旧的 `toString` 方法和新的 `toGenericString` 方法。 旧方法主要是为了向后兼容性而维护的。 示例 `7-3` 中显示了一个小样本类,示例 `7-4` 中显示了使用此类运行的示例。
6+
7+
`7-2`。 对泛型的反思
8+
9+
```java
10+
import java.lang.reflect.*;
11+
import java.util.*;
12+
class ReflectionForGenerics {
13+
public static void toString(Class<?> k) {
14+
System.out.println(k + " (toString)");
15+
for (Field f : k.getDeclaredFields())
16+
System.out.println(f.toString());
17+
for (Constructor c : k.getDeclaredConstructors())
18+
System.out.println(c.toString());
19+
for (Method m : k.getDeclaredMethods())
20+
System.out.println(m.toString());
21+
System.out.println();
22+
}
23+
public static void toGenericString(Class<?> k) {
24+
System.out.println(k + " (toGenericString)");
25+
for (Field f : k.getDeclaredFields())
26+
System.out.println(f.toGenericString());
27+
for (Constructor c : k.getDeclaredConstructors())
28+
System.out.println(c.toGenericString());
29+
for (Method m : k.getDeclaredMethods())
30+
System.out.println(m.toGenericString());
31+
System.out.println();
32+
}
33+
public static void main (String[] args) throws ClassNotFoundException {
34+
for (String name : args) {
35+
Class<?> k = Class.forName(name);
36+
toString(k);
37+
toGenericString(k);
38+
}
39+
}
40+
}
41+
```
42+
43+
`7-3`。 示例类
44+
45+
```java
46+
class Cell<E> {
47+
private E value;
48+
public Cell(E value) { this.value=value; }
49+
public E getValue() { return value; }
50+
public void setValue(E value) { this.value=value; }
51+
public static <T> Cell<T> copy(Cell<T> cell) {
52+
return new Cell<T>(cell.getValue());
53+
}
54+
}
55+
```
56+
57+
`7-4`。 示例运行
58+
59+
```java
60+
% java ReflectionForGenerics Cell
61+
class Cell (toString)
62+
private java.lang.Object Cell.value
63+
public Cell(java.lang.Object)
64+
public java.lang.Object Cell.getValue()
65+
public static Cell Cell.copy(Cell)
66+
public void Cell.setValue(java.lang.Object)
67+
class Cell (toGenericString)
68+
private E Cell.value
69+
public Cell(E)
70+
public E Cell.getValue()
71+
public static <T> Cell<T> Cell.copy(Cell<T>)
72+
public void Cell.setValue(E)
73+
```
74+
75+
示例运行表明,尽管对象和类标记的实体化类型信息不包含有关泛型的信息,但该类的实际字节码确实可以对有关泛型和擦除类型的信息进行编码。 关于泛型类型的信息本质上是一个评论。 运行代码时将被忽略,并且仅保留用于反射。
76+
77+
不幸的是,类 `Class` 没有 `toGenericString` 方法,尽管这会很有用。 `Sun` 正在考虑在未来增加这种方法。 同时,所有必要的信息都是可用的,我们将在下一部分解释如何访问它。
78+
79+

0 commit comments

Comments
 (0)