001 /* JAPI - (Yet another (hopefully) useful) Java API 002 * 003 * Copyright (C) 2004-2006 Christian Hujer 004 * 005 * This program is free software; you can redistribute it and/or 006 * modify it under the terms of the GNU General Public License as 007 * published by the Free Software Foundation; either version 2 of the 008 * License, or (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013 * General Public License for more details. 014 * 015 * You should have received a copy of the GNU General Public License 016 * along with this program; if not, write to the Free Software 017 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 018 * 02111-1307, USA. 019 */ 020 021 package net.sf.japi.lang; 022 023 import java.util.Iterator; 024 import java.util.NoSuchElementException; 025 import org.jetbrains.annotations.Nullable; 026 027 /** An Iterator for iterating through the superclasses (subclasses to superclasses) of a class. 028 * Note: The supplied class is included in iteration. If you want to omit it, you'll have to invoke getSuperclass() once, e.g. use <code>new SuperClassIterator(clazz.getSuperClass())</code> instead of <code>new SuperClassIterator(clazz)</code>. 029 * @author <a href="mailto:chris@riedquat.de">Christian Hujer</a> 030 */ 031 public class SuperClassIterator implements Iterator<Class<?>>, Iterable<Class<?>> { 032 033 /** The current class. */ 034 @Nullable private Class<?> nextClass; 035 036 /** Create a SuperClassIterator. 037 * @param clazz Class to create Iterator for 038 */ 039 public SuperClassIterator(@Nullable final Class<?> clazz) { 040 nextClass = clazz; 041 } 042 043 /** {@inheritDoc} */ 044 public boolean hasNext() { 045 return nextClass != null; 046 } 047 048 /** {@inheritDoc} */ 049 public Class<?> next() { 050 if (nextClass == null) { 051 throw new NoSuchElementException(); 052 } 053 try { 054 return nextClass; 055 } finally { 056 nextClass = nextClass.getSuperclass(); 057 } 058 } 059 060 /** {@inheritDoc} */ 061 public void remove() { 062 throw new UnsupportedOperationException(); 063 } 064 065 /** {@inheritDoc} */ 066 public Iterator<Class<?>> iterator() { 067 return this; 068 } 069 070 } // class ClassIterator