Overriding an enum type?

Hi Java experts,
I would appreciate some help about a small problem I have with some java code of my own. I'm using Java 1.5. I currently have written a class that takes a filename and extract records from a corresponding binary file. The structure of the file is known and is stored in a enum:
public class ParseFile  {
    private static enum TicketField {
        FieldA(1, FieldType.TYPE_INT),
        FieldB(1, FieldType.TYPE_INT),
        FieldC(2, FieldType.TYPE_STRING),
        // Stores number of fields in record. BTW is this the right way to do it ?
        public static final int numberOfElements = TicketField.values().length;
        // Length of field in bytes.
        private int size;
        // Type of field, enumerated.
        private FieldType type;
        // Constructor.
        TicketField(int size, FieldType type) {
            this.size = size;
            this.type = type;
    public ARRAY fetchRows(String filename) {
    // Create a new row structure.
    Vector<Object> row = new Vector<Object>(TicketField.numberOfElements);
    // Extract rows according to definition of fields above.
    blah blah
    }With this code I can call fetchRows('my_file') and get the list of records in it. Now I would like to extend this piece of code to be able to process different types of files, with different number of fields, different fields definitions, etc; however the extraction algorithm, once the file structure is given, remains the same. I would eg call fetchRows('my_file_cll', type='cll'), fetchRows('my_file_cat', type='cat'), etc. The structure of the returned resultsets would differ btw.
So conceptually I would like to subclass ParseFile, overriding not the method (fetchRows) but the enum... I can't think of a way to do this. Is it possible to define a kind of "abstract enum" that would be used in the code but instanciated only in a subclass? Otherwise is there a neat way to obtain this result in Java, avoiding to duplicate the code n times?
Thanks for your help,
Chris

Maybe something on the lines ofpublic class EnumFieldTest<E extends Enum<E>>     {
  private final Enum<E>[] myEnum;
  public EnumFieldTest(Enum<E>[] myEnum) {
    this.myEnum = myEnum;
  public void printEnumValues() {
    for (Enum<E> enum1 : myEnum) {
      System.out.println(enum1);
  public static void main(String[] args) {
    new EnumFieldTest<TicketField>(TicketField.values()).printEnumValues();
enum TicketField {
  FieldA, FieldB, FieldC
}db

Similar Messages

  • Int to enum type loookup

    I am iterating in a while loop and using the index terminal to build an array of differnet values of the same enumerated type control that are from a strict type def enumerated control. What I want to do is to iterate and do a comparison and if the comparison holds, I want to build an array of the correlating enumerated types so that I can use this later on.
    I am using a Function that came with the state diagram toolkit called "int to enum" that the state diagram uses when calculating its next state info. It seems to bomb out when I attempt to wire my enum type control to its input.
    Any ideas?

    I have not used the state diagram toolkit but have extensively employed enums from typedefs. This is very convenient since for comparisons just compare it to a constant version of the typedefs. If you use a strict typedef remember that almost everything must be identical and this causes many problems. Since typedefs of enums rarely have to be strict I would think about why you chose a strict type def as opposed to a normal typedef. One additional added feature is that when wiring a enum typedef to a case structure you can populate the case with the enum named cases. I would speculate that your problems are due to the use of a strict typedef which is only necessary when you are concerned with more than just a typdef's structure and values (i.e aesthetic properties). Hope this helps (again I have not used the state diagram toolkit).
    -Paul
    Paul Falkenstein
    Coleman Technologies Inc.
    CLA, CPI, AIA-Vision
    Labview 4.0- 2013, RT, Vision, FPGA

  • Query on conversion between String to Enum type

    Hi All,
    I would like to get advice on how to convert between char and Enum type. Below is an example of generating unique random alphabet letters before converting them back to their corresponding letters that belonged to enum type called definition.Alphabet, which is part of a global project used by other applications:
    package definition;
    public enum Alphabet
    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S,
    T, U, V, W, X, Y, Z
    public StringBuffer uniqueRandomAlphabet()
    String currentAlphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    StringBuffer randomAlphabetSB = new StringBuffer();
    for (int numberOfAlphabet=26; numberOfAlphabet>0; numberOfAlphabet--)
    int character=(int)(Math.random()* numberOfAlphabet);
    String characterPicked = currentAlphabet.substring(character, character+1);
    // System.out.println(characterPicked);
    randomAlphabetSB.append(characterPicked);
    StringBuffer remainingAlphabet = new StringBuffer( currentAlphabet.length() );
    remainingAlphabet.setLength( currentAlphabet.length() );
    int current = 0;
    for (int currentAlphabetIndex = 0; currentAlphabetIndex < currentAlphabet.length(); currentAlphabetIndex++)
    char cur = currentAlphabet.charAt(currentAlphabetIndex);
    if (cur != characterPicked.charAt(0))
    remainingAlphabet.setCharAt( current++, cur );
    currentAlphabet = remainingAlphabet.toString();
    return randomAlphabetSB;
    // System.out.println(randomAlphabetSB);
    I got the following compilation error when trying to pass (Alphabet) StringBuffer[0] to a method that expects Alphabet.A type:
    inconvertible types
    required: definition.Alphabet
    found: char
    Any ideas on how to get around this. An alternative solution is to have a huge switch statement to assemble Alphabet type into an ArrayList<Alphabet>() but wondering whether there is a more shorter direct conversion path.
    I am using JDK1.6.0_17, Netbeans 6.7 on Windows XP.
    Thanks a lot,
    Jack

    I would like to get advice on how to convert between char and Enum type. Below is an example of generating unique random alphabet lettersIf I understand well, you may be interested in method shuffle(...) in class java.util.Collections, which randomly reorders a list.
    before converting them back to their corresponding letters that belonged to enum type called definition.AlphabetIf I understand well, you may be interested in the built-in method Alphabet.valueOf(...) which will return the appropriate instance by name (you'll probably have no problem to build a valid String name from a lowercase char).

  • % operator in Enum Type

    Dear fellow developers,
    Below is code calculating your weight on different planets using Enum type, from the book of Sun on Java Tutorials. Can anyone tell me what does "%" mean in "%s", "%f" and "%n"?
    How does all three managed to get in the for-each loop without being declared explicitly before it?
    public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS (4.869e+24, 6.0518e6),
    EARTH (5.976e+24, 6.37814e6),
    MARS (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27, 7.1492e7),
    SATURN (5.688e+26, 6.0268e7),
    URANUS (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO (1.27e+22, 1.137e6);
    private final double mass; // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
    this.mass = mass;
    this.radius = radius;
    private double mass() { return mass; }
    private double radius() { return radius; }
    // universal gravitational constant (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;
    double surfaceGravity() {
    return G * mass / (radius * radius);
    double surfaceWeight(double otherMass) {
    return otherMass * surfaceGravity();
    public static void main(String[] args) {
    double earthWeight = Double.parseDouble(args[0]);
    double mass = earthWeight/EARTH.surfaceGravity();
    for (Planet p : Planet.values())
    System.out.printf("Your weight on %s is %f%n",
    p, p.surfaceWeight(mass));
    Thank you in advance.

    DanielTan_NL wrote:
    How does all three managed to get in the for-each loop without being declared explicitly before it?They are declare. Right here.
    >
    public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS (4.869e+24, 6.0518e6),
    EARTH (5.976e+24, 6.37814e6),etc.
    Every enum has a values() method that returns an array of the values you define for that enum.

  • Can enum type be used in web service

    I am confused about how to use a enum type in web service interface, please do me the favor

    yep, that I assumed that was the category. I meant, What are you trying to do? Is this a webservices specific question or a question about how to use Sun Java Studio Enterprise and Web Service?? If this is a Web Services specific question, try posting to the Web Services forum.
    http://forum.java.sun.com/forum.jspa?forumID=331
    I searched this forum for postings related to your question but did not find much.

  • Why java take enum type off

    why java take enum type off?
    When in switch statement, it become complex without enum type.
    Enum can constrained the range of integer value. Taking enum type off,
    method parameter checking will take lots effort.
    can any way to replace the functions of enum type.

    It was a disputable design decision.
    The original C "enum" type is however somewhat flawy from its lack of encapsulation (its elements "pollute the global namespace" - they are for this purpose!) and would not seamless fit into the typed, OO Java philosophy.
    Otherwise put, the original "C" enum fits well to the C philosophy but no to the C++ or Java one.

  • Enum type is retrieving me a null reference

    Hi, i have a very strange bug in my code that is messing me up.
    I defined two enum types in separated files like this:
    public enum Section {
         SectionA, SectionN;
    public enum Subsection {
        SubA(1, SectionA), SubN(2, SectionN);
        private Section sec;
        private int num;
        Subsection (int num, Section sec) {
            this.num = num;
            this.sec = sec;    // Here is the problem
    }Well, the problem is that in the line with the comment I'm recieving a null reference and I think that is not possible. Is that a compiler bug?

    I'm no getting any error message, let me show you my code:
    The problematic enum type.
    public enum Subseccion {
        ALUMNOS_ALTA(1, AltaAlumnos.class, "Alta", Privilegio.ALTA_ALUMNOS, Seccion.ALUMNOS),
        ALUMNOS_BUSCAR(2, BuscarAlumno.class, "Buscar", Privilegio.BUSCAR_ALUMNOS, Seccion.ALUMNOS),
        ALUMNOS_EDITAR(3, EditarAlumno.class, "Editar", Privilegio.EDITAR_ALUMNOS, Seccion.ALUMNOS),
        PERSONAL_ALTA(1, AltaPersonal.class, "Alta", Privilegio.ALTA_PROFESORES, Seccion.PERSONAL),
        PERSONAL_BUSCAR(2, BuscarPersonal.class, "Buscar", Privilegio.PERSONAL_BUSCAR, Seccion.PERSONAL),
        PERSONAL_EDITAR(3, EditarPersonal.class, "Editar", Privilegio.PERSONAL_EDITAR, Seccion.PERSONAL),
        MATERIAS(1, Materias.class, "Materias", Privilegio.ASIGNATURAS, Seccion.CURSOS),
        CURSOS(2, Cursos.class, "Cursos", Privilegio.CURSOS, Seccion.CURSOS),
        GRUPOS(3, Grupos.class, "Grupos", Privilegio.GRUPOS, Seccion.CURSOS),
        ASIGNAR_GRUPOS(4, AlumnosSalones.class, "Asignar Grupos", Privilegio.ASIGNAR_GRUPOS, Seccion.CURSOS);
        private final Class<? extends JPanel> panel;
        private final String texto;
        private final Seccion pa;  // La secci�n a la que pertenece
        private final Privilegio priv;   
        private final int importancia;
        Subseccion(int importa, Class<? extends JPanel> panel, String texto, Privilegio priv, Seccion fad) {
            this.panel = panel;
            this.texto = texto;
            if (fad == null)
                System.err.println("A NULL REFERENCE");   // Always happen
            pa = fad;
            this.priv = priv;
            this.importancia = importa;
        public int getImportancia() {
            return importancia;
         * Regresa el Panel construido que corresponde a la secci�n.
         * @param d El Objeto de base de datos que se usar� para crear el Panel.
         * @param ven El Objeto de ventana que se usar� para crear el Panel.
        public JPanel getPanelInstance(BaseDeDatosE d, VentanaPrincipal ven)
            throws InstantiationException, NoSuchMethodException, IllegalAccessException,
                    java.lang.reflect.InvocationTargetException {
            // Construyo el panel si es que hay uno asociado
            Constructor<? extends JPanel> cons = panel.getConstructor(BaseDeDatosE.class, VentanaPrincipal.class);
            JPanel panel = cons.newInstance(d, ven);
            return panel;
         * Devuelve el privilegio asociado a esta secci�n.
        public Privilegio getPrivilegio() {
            return priv;
         * Pone el "bot�n" en RollOver.
         * @param btn El "bot�n"
        public void setEstadoRollOver(JPanel btn) {
         * Pone el "bot�n" en estado presionado.
         * @param btn El "bot�n"
        public void setEstadoPresionado(JPanel btn) {
         * Devuelve la secci�n a la que pertenece.
        public Seccion getSec() {
            return pa;
         * Pone el "bot�n" en estado normal.
         * @param btn El "bot�n"
        public void setEstadoNormal(JPanel btn) {
    The enum type that is getting null.
    public enum Seccion {
        ALUMNOS(null, "/alumno", "Alumnos",
                new Subseccion[] {Subseccion.ALUMNOS_BUSCAR, Subseccion.ALUMNOS_ALTA, Subseccion.ALUMNOS_EDITAR},
                null),
        PERSONAL(null, "/profesor", "Personal",
                 new Subseccion[] {Subseccion.PERSONAL_BUSCAR, Subseccion.PERSONAL_ALTA, Subseccion.PERSONAL_EDITAR},
                 null),
        CURSOS(null, "/cursos", "Cursos",
               new Subseccion[] {Subseccion.CURSOS, Subseccion.GRUPOS, Subseccion.MATERIAS, Subseccion.ASIGNAR_GRUPOS},
               null),
        CURSOS_CALIFICAR(CalificarCursos.class, "/default", "Calificar Cursos", null, Privilegio.CALIFICAR_CURSOS),
        ASISTENCIA(Asistencia.class, "/default", "Asistencia", null, Privilegio.ASISTENCIA);
        private final Class<? extends JPanel> panel;
        private final String prefijoImagen;
        private final Subseccion[] subs;  // Las subseciones de esta secci�n
        private final String etiqueta;  // El texto que va a llevar el icono
        private final Privilegio priv;
        Seccion (Class<? extends JPanel> panel, String prefijoImagen, String etiqueta, Subseccion[] subs, Privilegio priv) {
            this.panel = panel;
            this.prefijoImagen = prefijoImagen;
            this.subs = subs;
            this.etiqueta = etiqueta;
            this.priv = priv;
         * Regresa el Panel construido que corresponde a la secci�n.
         * @param d El Objeto de base de datos que se usar� para crear el Panel.
         * @param ven El Objeto de ventana que se usar� para crear el Panel.
         * @return <code>null</code> Si no tiene un panel asociado.
        public JPanel getPanelInstance(BaseDeDatosE d, VentanaPrincipal ven)
            throws InstantiationException, NoSuchMethodException, IllegalAccessException,
                    java.lang.reflect.InvocationTargetException {
            if (panel != null) {
                // Construyo el panel si es que hay uno asociado
                Constructor<? extends JPanel> cons = panel.getConstructor(BaseDeDatosE.class, VentanaPrincipal.class);
                JPanel panel = cons.newInstance(d, ven);
                return panel;
            return null;
         * Devuelve el privilegio asociado a esta secci�n.
         * @return <code>null</code> Si no existe un privilegio asociado.
        public Privilegio getPrivilegio() {
            return priv;
         * Pone el icono de estado RollOver.
         * @param etiq El JLabel asociado a esta secci�n
        public void setIconoRollOver(JLabel etiq) {
            etiq.setIcon( new ImageIcon( getClass().getResource(prefijoImagen + "BtnOver.jpg") ) );
         * Pone el icono de estado Presionado.
         * @param etiq El JLabel asociado a esta secci�n
        public void setIconoPresionado(JLabel etiq) {
            etiq.setIcon( new ImageIcon( getClass().getResource(prefijoImagen + "Btn.jpg") ) );
         * Pone el icono de estado Normal.
         * @param etiq El JLabel asociado a esta secci�n
        public void setIconoNormal(JLabel etiq) {
            etiq.setIcon( new ImageIcon( getClass().getResource(prefijoImagen + "BtnBco.jpg") ) );           
         * Obtiene un arreglo con las subsecciones disponibles, en primer lugar la que
         * se deber�a mostrar por defecto.
         * @return <code>null</code> Si no tiene subsecciones asociadas.
        public Subseccion[] getSubsecciones() {
            return subs;
         * Le pone el texto a la etiqueta que muestra el icono de la secci�n.
        public void setTextoIcono(JLabel etiq) {
            etiq.setText(etiqueta);
    }And if you do
    Subseccion.ALUMNOS_ALTA;The message "NULL REFERENCE" is printed.

  • Enum type

    Hi,
    I have tried to add an enum type to my app but the IDE shows an error!
    Unexpected token identifier.
    My JDeveloper version is 10.1.3 and the Java platform component version is 1.5.6
    Any ideas?
    Thanks in advance.

    I have set a new project, with Database, EJB and Java technologies for the scope.
    The business uses JPA/EJB3 for the tables generation.
    I need to add an enum in the project so I have created a new .java file as follows
    public enum State{
    OPEN, CLOSED
    This file wont compile because the IDE says the token is not recognized.
    Is there any configuration I'm missing in my project?

  • Enum type class hierarchy.

    Hi,
    I was reviewing and eagerly testing the Typesafe Enum Facility (enum types) on 1.5.0 beta, which is still in Public Review in the JCP (JSR-201).
    I would would like to mention a missing feature that I find usefull and powerfull for a custom framework architecture.
    I understand and agree with respect to the first question on the JSR 201 FAQ, about subclassing enums.
    Having enumeration constants from both the superclass and the subclass is quite confusing and I agree with disallowing it from the language.
    But I miss the ability to inherit custom behavior (methods, and not enumeration constants), for an enum type, from a middle superclass. This middle superclass could be a base class for enum types within a specific development framework (and of course, java.lang.Enum would by in is class hierachy).
    The actual proposal allows for an enum type to only have java.lang.Enum as superclass, from which it inherits methods like name() and ordinal(). But in a proyect where a large number of diferent enum types with a common and custom extra framework behavior (like a localizedName() or propertyKey() method for example) would need the implementation of this behavior in each enum type source code (or in a helper class).
    Following the example above, the actual proposal would need the following coding in order to add an additional behavior to all (or some) of the enum types in a development proyect:
    public interface MyBaseFrameworkEnum {
         String localizedName();
         String propertyKey();
    public enum FooEnum implements MyBaseFrameworkEnum {
         FOO_A, FOO_B;
         public String localizedName() {
              //..... coding necesary in every enum implementing BaseFrameworkEnum
         public String propertyKey() {
              //..... coding necesary in every enum implementing BaseFrameworkEnum
    As you see, every enum type in my example framework (like FooEnum) would need to code both methods localizedName() and propertyKey() which would produce a lack of centralized code and increase of class file size.
    It would be very powerfull to be able to use the following coding:
    public abstract enum MyBaseFrameworkEnum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    As you see, with this abstract enum MyBaseFrameworkEnum (which does not falls in the subclassing problem mentioned in the FAQ) does not define enum constants and will pass its custom behavior to its subclass enums. thus centralizing the related code.
    I generally use an implementation of the Typesafe Enum Pattern so I really am looking forward for this new Typesafe Enum Facility in the Java language. But, as an example, I generally use common features in my enums, a properyKey() method used to get a unique key in order to internationalize my applications, since a description to enums is normally needed to be displayed to users.
    I believe this capability would be very powerfull in cases where common features are needed for enums in a development proyect with respect of:
    - code centralization and maintainance.
    - class file size.
    - source code readability.
    This extension would not contradict the actual definition, it would only allow for an enum type to be able to extend from another abstract enum type which has no enumeration constants.
    I believe that if there are other programmers that find this extension worth, it could make it in the JSR-201(which is in public review until February 21th) process before the final specification.
    Regards,
    Luis Longeri

    It would be very powerfull to be able to use the
    following coding:
    public abstract enum MyBaseFrameworkEnum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    }Luis, I like your idea but don't really like the idea of an abstract enum. I think this would be better
    public class MyBaseFrameworkEnum extends Enum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    }However, this always opens up the risk of you breaking the enum specific stuff, so all the vulnerable Enum methods would need to be declared "final".
    Because you are unlikely to see this in the language any time soon (if at all), you can always centralise your code in some static methods that take the enum as an argument
    public class MyBaseFrameworkEnumTools {
         public String localizedName(Enum e) {
              //..... coding centralized
         public String propertyKey(Enum e) {
              //..... coding centralized

  • Enum type as generic

    In the following, what should X be so that E is recognized as an enum type?
    class A<E extends X> {
        . . . E.values() . . .
    }It seems that X of Enum<E> should work, but no joy. I thought that enum types were subclasses of java.lang.Enum, but apparently not fully.

    Enum<E> does not have a method values(). The compiler generates this method for every enum, but it is not declared in Enum.
    It can't be declared in Enum because it is static, and in Enum it would also be abstract (it is not implemented there), but static and abstract are incompatible modifiers.
    Even though we know it will always work, the language has no way to specify that every Enum<E> has that method, and so you can't call it on a type variable.
    As a solution (if you really need this to work), put a Class<E> argument in the constructor, save the Class<E> reference, use reflection on the reference to get values().class A<E extends Enum<E>> {
        Class<E> type;
        A(Class<E> type) { this.type = type; }
        void yourMethod() {
            E[] values=type.getMethod("values").invoke(null);
    }You'll need to deal with a few exceptions but they shouldn't in practice get thrown.
    Bruce

  • Enum types not supported in jws

    I'm using wls 10.3 and one of my java class has a property that used a java enum type and when I tried to run jwsc, I'm getting this error message:
    [jwsc] [ERROR] - Enum Types are not supported on a JWS: com.starcomsoft.pp.vo.RecordStatus
    [jwsc] C:\starcomsoft\jax-rpc-103-test117\source\server\com\starcomsoft\pp\order\jws\OrderWSImpl.java 205
    :21
    How can I fix this problem. Thanks for you help

    Thanks for reporting this problem! I have filed bug 18499900.
    BTW, according to the C++11 standard, the code is actually not valid. Section 6.4.2, switch statement, says an implicit conversion to an integral type is required, which is not the case for for a scoped enum (one using the "class enum" syntax). This limitation was raised in the C++ Committee as an issue to be fixed, and the C++14 standard makes the code valid.
    As a workaround, or to make the code conform to C++11, you can add casts to int for the enum variable and the enumerators.
    Message was edited by: Steve_Clamage

  • Passing enums to functions without knowing the specific enum type

    My application needs the function invocation feature by using reflection mechanism. The function parameters are restricted to string, int, float and enums. I am facing problems with enums.
    Is there a way to invoke the function by passing specific enum type as parameter to the function.
    For eg:
    public void doProcess(int i, COLOR.RED){
    I should be able to invoke the above function using reflections. How dynamic casting to COLOR can be done is the question here?

    The application takes XML file as an input. This file has processing instructions. The processing instruction provides data about the class name, function name and parameters specifications like
    Classname_FunctionName("String param", 123, COLOR.RED)
    The application should invoke the corresponding library function by passing these parameters after assessing the correct types.

  • Reflection and enum types: help needed

    Hello, I just released a new version of my OpenSource project (http://sourceforge.net/projects/jdbcmanager).
    The application needs JRE 1.5 just only for printing tables (JTable.getPrintable(...) method).
    I have had a lot of complains from users due to requiring 1.5
    So I'm trying to make it compatible with 1.4.2 and also provide JTable printing functionality to 1.5 users.
    I can check if JRE in use is 1.5 and then invoke getPrintable(...) method via reflection, but I do not find a way to pass its first argument (an enum) via reflection, because in 1.4.x enum type does not exist, and without solving this the compiler reports a compilation error.
    Here is the code I'm using:String sJavaVer = System.getProperty( "java.version" );
           if( sJavaVer.charAt( 0 ) == '1' && sJavaVer.charAt( 2 ) < '5' )
               MessageFormat mfHeader = new MessageFormat( sHeader );
               MessageFormat mfFooter = new MessageFormat( sFooter );
               Printable     p        = getPrintable( PrintMode.FIT_WIDTH, mfHeader, mfFooter );
               PrintShop     ps       = new PrintShop( p );
               if( bPreview )
                   ps.showPreview( "Preview: "+ sHeader, getPreferredScrollableViewportSize() );
               else
                   ps.print( bPageDialog );
           else
               App.showMessage( "Warning", "You need JRE 1.5.0 or above to be able to print tables." );
           }Obviously this can't compile under 1.4.x
    Every suggestion is more than welcome.

    I haven't worked with 1.5 enums, but my best guess is that you'd have to get instances of the enums via reflection as well.
    As an incidental suggestion: rather than doing a text search on the "java.version" property, you should simply try to retrieve the "getPrintable" method via reflection. The "if" condition then checks to see if you got anything back.

  • Passing any enum type to a method

    Consider I have created some enums:
    public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
    public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
    }I want to create a method that will accept any type of enum and display all values. So the call would look something like:
    showAll(Day);
    showAll(Month);I'm not sure what to pass to the method. My understanding of Generics is rudimentary at best, despite reading the tutorial several times now. Here is some uncompilable code that might illustrate:
    public void showAll(EnumType enumType)  // <--- not sure what to pass here
      Enum[] allValues = enumType.values();
      // then, loop over the allValues array and I can proceed from here
    }The actual code is needed is for displaying a list of checkboxes to the user where the input is the enum class, and the checkboxes are every enum value.

    brucechapman wrote:
    You could use this signature
    <T extends Enum<T>> void showall(Class<T> clazz); Then use reflection to invoke the values() method which you know is there because only Class objects for enums can be passed in.I'll be honest, that signature looks very strange to me. However, I tried it anyway and it worked even without reflection.
    public class PassingEnums
      public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
      public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
      public <T extends Enum<T>> void showAll(Class<T> clazz)
        T[] types = clazz.getEnumConstants();
        for (int i = 0; i < types.length; i++)
          System.out.println(types.toString());
    public static void main(String[] args)
    PassingEnums test = new PassingEnums();
    test.showAll(Day.class);
    System.out.println("---");
    test.showAll(Month.class);
    }Or were you thinking of something else?
    I guess I'll have to hit the tutorials again, since that signature looks foreign to me.
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Pass enum type as a paramter of constructor

    hi
    i have a hospital system application with three main classes Patient, Doctor and Hospital as well as two Enum classes. The Hospital class uses the Patient class's constructors to create object. The parameters that Patient class default constructor takes are-
    private Patient(String name, int age, Type patientType, String medicareNo, int hoursTreated) { //set class fields}
    now when i actually use this in the hospital class , like -
    hospital.patients.add(new Patient ("Fred Bear", 29, PRIVATE, "Ben Casey", "HCF236788", 10, Level.A));
    i get error in Netbeans and Eclipse that constuctor not found
    can anyone plz tell me how to solve this one!!!
    thnx

    karanJ wrote:
    can anyone plz tell me how to solve this one!!!
    Either by passing arguments that match an existing c'tor in number and types of args or by creating a new constructor that matches what you're trying to call in number and types of args. Which one is correct depends on your requirements, so only you know that.

Maybe you are looking for