为了账号安全,请及时绑定邮箱和手机立即绑定

java泛型的一些小问题

java泛型的一些小问题

守候你守候我 2019-02-20 16:31:20
不多说废话,先上代码 class Apply { // 必须放置边界和通配符,银边使得Apply和FilledList在所有需要的情况下都可以使用,否则,下面的某些Apply和FilledList应用将无法工作。 public static <T, S extends Iterable<? extends T>> /*List<Shape> shapes = new ArrayList<Shape>(); 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<T> extends ArrayList<T> { // 类型标记技术是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<Shape> shapes = new ArrayList<Shape>(); 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<Square> squares = new ArrayList<Square>(); 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>(Shape.class, 10), Shape.class.getMethod("rotate")); Apply.apply(new FilledList<Shape>(Square.class, 10), Shape.class.getMethod("rotate")); } } 经过编译发现上面这段代码是可以运行的,但是对这语句很困惑:public static <T, S extends Iterable<? extends T>>那位表哥能解释下具体的意思,以及泛型T是如何来进行赋值的,感激不尽
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

不是赋值,而是在编译时指定某个类型,比如调用时apply(new Integer(1),Arrays.asList(1,2,3)), T就是 Integer

查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 538 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号