不多说废话,先上代码
class Apply {
// 必须放置边界和通配符,银边使得Apply和FilledList在所有需要的情况下都可以使用,否则,下面的某些Apply和FilledList应用将无法工作。
public static >
/*List shapes = new ArrayList();
Apply.apply(shapes, Shape.class.getMethod("rotate"));*/
void apply(S seq, Method f, Object... args) {
try {
for(T t: seq)
f.invoke(t, args);
} catch(Exception e) {
// Failures are programmer errors
throw new RuntimeException(e);
}
}
}
class Shape {
public void rotate() { System.out.println(this + " rotate"); }
public void resize(int newSize) {
System.out.println(this + " resize " + newSize);
}
}
class Square extends Shape {}
class FilledList extends ArrayList {
// 类型标记技术是Java文献推荐的技术。但是,有些人强烈地首先工厂方式
public FilledList(Class extends T> type, int size) {
try {
for(int i = 0; i < size; i++)
// Assumes default constructor:
add(type.newInstance());
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
public class Chapter15_17_2 {
public static void main(String[] args) throws Exception {
List shapes = new ArrayList();
for(int i = 0; i < 10; i++)
shapes.add(new Shape());
Apply.apply(shapes, Shape.class.getMethod("rotate"));
Apply.apply(shapes,
Shape.class.getMethod("resize", int.class), 5);
List squares = new ArrayList();
for(int i = 0; i < 10; i++)
squares.add(new Square());
Apply.apply(squares, Shape.class.getMethod("rotate"));
Apply.apply(squares,
Shape.class.getMethod("resize", int.class), 5);
Apply.apply(new FilledList(Shape.class, 10),
Shape.class.getMethod("rotate"));
Apply.apply(new FilledList(Square.class, 10),
Shape.class.getMethod("rotate"));
}
}
经过编译发现上面这段代码是可以运行的,但是对这语句很困惑:public static >
那位表哥能解释下具体的意思,以及泛型T是如何来进行赋值的,感激不尽