View Javadoc

1   /*
2    * Copyright 2004-2005 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    * 
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package net.sf.morph.reflect.support;
17  
18  import java.util.Iterator;
19  import java.util.NoSuchElementException;
20  
21  import net.sf.composite.util.ObjectUtils;
22  
23  /**
24   * Exposes an object as an iterator by treating the object as a collection with
25   * one element. That means <code>hasNext</code> will return <code>true</code>
26   * before <code>next</code> has been called, and will return
27   * <code>false</code> after it has been called.
28   * 
29   * @author Matt Sgarlata
30   * @since Jan 8, 2005
31   */
32  public class ObjectIterator implements Iterator {
33  	private static final String NSEE = "There is only one element in a "
34  			+ ObjectUtils.getObjectDescription(ObjectIterator.class);
35  
36  	private Object object;
37  	private boolean hasNext = true;
38  
39  	public ObjectIterator(Object object) {
40  		this.object = object;
41  	}
42  
43  	public void remove() {
44  		throw new UnsupportedOperationException();
45  	}
46  
47  	public boolean hasNext() {
48  		return hasNext;
49  	}
50  
51  	public Object next() {
52  		if (!hasNext) {
53  			throw new NoSuchElementException(NSEE);
54  		}
55  		hasNext = false;
56  		return object;
57  	}
58  
59  }