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

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /