package swordOffre.gaopengyu; import java.lang.reflect.Method; import java.util.Stack; class QueueWith2Stack<T> { Stack<T> stack1 = new Stack(); Stack<T> stack2 = new Stack(); public void appendTail(T element) { stack1.push(element); } public T deleteHead() throws queueEmptyException { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } if (stack2.isEmpty()) { throw new queueEmptyException("队列已经为空"); } return (T) stack2.pop(); } } class queueEmptyException extends Exception { String str; queueEmptyException(String str) { this.str = str; } @Override public String toString() { return this.str; } } public class GenerateQueueWith2Stack { public static void main(String[] args) { QueueWith2Stack<Integer> queue = new QueueWith2Stack(); queue.appendTail(1); // queue.appendTail("string"); //使用反射越过泛型检查 try { Class QueueWith2StackClass = Class.forName("swordOffre.gaopengyu.QueueWith2Stack"); Method m = QueueWith2StackClass.getMethod("appendTail", Object.class); m.invoke(queue, "string"); } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < 4; i++) { try { System.out.println(queue.deleteHead()); } catch (queueEmptyException qe) { System.out.println(qe.toString()); } } } }