Java code for Enumeration and using java.lang.reflect.Array
By: Saravanan
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
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java