15.3 泛型接口

来源:互联网 发布:网络新词及意思和出处 编辑:程序博客网 时间:2024/03/29 19:05

泛型也可以用于接口, 下面显示了一个随机Robot访问器的示例, 实现了一个自定义的Generator泛型接口

package com.cnsuning.src;import java.lang.reflect.*;import java.util.*;public class Main {public static void main(String[] args) {RobotGenerator rg = new RobotGenerator();for(Robot robot: rg){System.out.println(robot);}}}class Robot {private static int count = 0;private int id = count++;public String toString(){return this.getClass().getSimpleName()+" "+id;}}class T100 extends Robot{}class Gundam extends Robot{}class Freedom extends Gundam{}class Striker extends Gundam{}class Zaku extends Robot{}interface IGenerator<T>{T next();}class RobotGenerator implements IGenerator<Robot>,Iterable<Robot>{private List<Class<? extends Robot>> classTypes = new LinkedList<Class<? extends Robot>>();{classTypes.add(Robot.class);classTypes.add(T100.class);classTypes.add(Gundam.class);classTypes.add(Freedom.class);classTypes.add(Striker.class);classTypes.add(Zaku.class);}private Random rand= new Random(47);private int maxLimit = 10;RobotGenerator(){}@Overridepublic Robot next() {int randIndex = rand.nextInt(classTypes.size());try {Robot randRobot = classTypes.get(randIndex).newInstance();return randRobot;} catch (InstantiationException | IllegalAccessException e) {// TODO Auto-generated catch blockthrow new RuntimeException(e);}}@Overridepublic Iterator<Robot> iterator() {// TODO Auto-generated method stubreturn new RobotIterator();}private class RobotIterator implements Iterator<Robot>{int count = maxLimit;@Overridepublic boolean hasNext() {return count>0;}@Overridepublic Robot next() {count--;return RobotGenerator.this.next();}@Overridepublic void remove() {// TODO Auto-generated method stubthrow new RuntimeException();}}}

测试结果:

Gundam 0
Zaku 1
T100 2
Zaku 3
T100 4
Zaku 5
Striker 6
Gundam 7
Robot 8
T100 9

0 0