package com.mindprod.example;
import java.lang.annotation.ElementType;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static java.lang.System.*;
/**
* Demonstrate use of general purpose enum code. In particular select a random value of an arbitrary enum.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2009-08-25 initial version
* @since 2009-08-25
*/
public class TestRandomEnum
{
/**
* wheel to generate random integers.
*/
private static final Random wheel = new Random();
/**
* get a randomly selected member of the enum. Works an any enum type.
*
* @param e a sample enum constant of the enum class.
*
* @return an randomly selected enum constant of the enum
*/
private static Enum<?> randomEnum( Enum<?> e )
{
return randomEnum( e.getDeclaringClass() );
}
/**
* Get a randomly selected member of the enum, given the class of the enum as a whole.
*
* @param clazz class of the enum as a whole.
*
* @return a randomly selected enum constant of the enum.
*/
private static <E extends Enum<E>> E randomEnum( Class<E> clazz )
{
E[] values = clazz.getEnumConstants();
return values[ wheel.nextInt( values.length ) ];
}
/**
* Test driver to exercise the methods in the class.
*
* @param args not used
*/
public static void main( String[] args )
{
out.println( "Possible TimeUnits: " );
for ( TimeUnit e : TimeUnit.values() )
{
out.println( " " + e );
}
out.println( "Random TimeUnit: " + randomEnum( TimeUnit.SECONDS ) );
out.println( "Possible ElementTypes: " );
for ( ElementType e : ElementType.values() )
{
out.println( " " + e );
}
out.println( "Random ElementType: " + randomEnum( ElementType.class ) );
}
}