开发者社区> 问答> 正文

java泛型的一些小问题 报错

"

不多说废话,先上代码

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是如何来进行赋值的,感激不尽

"

展开
收起
因为相信,所以看见。 2020-05-27 13:03:17 733 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

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

    2020-05-27 16:25:30
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载