Programming Tutorials

Java code for Enumeration and using java.lang.reflect.Array

By: Saravanan in Java Tutorials on 2010-01-01  

In this tutorial we are going to see how to use Enumeration in java.Enumeration is an interface so we have to implement it from util package. Enumeration specifies two methods. These are, boolean hasMoreElements(), Object nextElement().

Another important class is java.lang.reflect.Array;. eflection is the ability of program to analyze itself. This package provides the ability to obtain information about the fields, constructors, methods and modifiers of a class. And this package class enables you to create and access arrays dynamically.

import java.lang.reflect.Array;
import java.util.Enumeration;

public class EnumExample implements Enumeration
 {
  private final int i;

  private int j;

  private final Object o;

  public EnumExample(Object obj) 
  {
    Class classtype = obj.getClass();
    if (!classtype.isArray()) 
    {
      throw new IllegalArgumentException("Invalid type: " + classtype);
    }
    i = Array.getLength(obj);
    o = obj;
  }

  public boolean hasMoreElements() 
  {
    return (j < i);
  }

  public Object nextElement() 
  {
    return Array.get(o, j++);
  }

  public static void main(String args[]) 
  {
    Object obj = new int[] { 1, 2, 7, 9, 18, 27, 36 };
    EnumExample e = new EnumExample(obj);
    while (e.hasMoreElements()) 
    {
      System.out.println(e.nextElement());
    }
    try 
   {
      e = new EnumExample(EnumExample.class);
    } 
    catch (IllegalArgumentException ex) 
    {
      System.out.println(ex.getMessage());
    }
  }
}

Output:

1
2
7
9
18
27
36
Invalid type: class  java.lang.Class





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)