泛型也可以用于接口, 下面显示了一个随机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(){
}
@Override
public 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 block
throw new RuntimeException(e);
}
}
@Override
public Iterator<Robot> iterator() {
// TODO Auto-generated method stub
return new RobotIterator();
}
private class RobotIterator implements Iterator<Robot>{
int count = maxLimit;
@Override
public boolean hasNext() {
return count>0;
}
@Override
public Robot next() {
count--;
return RobotGenerator.this.next();
}
@Override
public void remove() {
// TODO Auto-generated method stub
throw new RuntimeException();
}
}
}
测试结果:
Gundam 0
Zaku 1
T100 2
Zaku 3
T100 4
Zaku 5
Striker 6
Gundam 7
Robot 8
T100 9