4

I need to provide some kind of facilities from enums and generics. Since enums cannot have type parameters (it's just forbidden by the grammar) and actually acts like public static final members I tend to write something like this:

public class GenericEnumLikeClass<T>{

    public static GenericEnumLikeClass<MyType> TYPE_INSTANCE;
    public static GenericEnumLikeClass<AnotherType> ANOTHER_INSTANCE;

    //other things
}

The thing is I've never done something similar before and strictly speaking not sure about the correctness from the Java Conventions standpoint. Will it be considered as something strange or it's a commmon technique used when we need to extend enum-like behavior with providing Type Paramters?

3 Answers 3

3

This is the technique that was used before Java 1.5 introduced enums, so it does not look strange. Older APIs have a lot of these enum-style classes. I would recommend to make the constructor private and provide a values() method that returns an array of all available instances.

Sign up to request clarification or add additional context in comments.

2 Comments

And don't forget the final modifier.
Although, there was no generics before Java 1.5
1

Agreed with @Ingo, you can use as constructor and provide a value() method just like:

public enum GenericEnumLikeClass { MyType("TYPE_INSTANCE"), AnotherType("ANOTHER_INSTANCE");

Comments

1

Don't know exactly what you want to do with your 'generic' argument, but this could give you some ideas:

Edit: As you don't explain how you use this generic parameter I could not give real example. Just add some methods, to explain what I have in mind:

public enum MyGenericEnum {

    TYPE_INSTANCE(MyClass.class),
    ANOTHER_INSTANCE(AnotherClass.class);

    private Class<? extends SomeSuperClass> clazz;

    private MyGenericEnum(Class<? extends SomeSuperClass> clazz) {
        this.clazz = clazz;
    }

    public Class<? extends SomeSuperClass> getType() {
        return clazz;
    }

    @SuppressWarnings("unchecked")
    public <T extends SomeSuperClass> T getObject() {
        try {
            return (T) clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

3 Comments

Unfortunately, ClassCastException will be discovered only at runtime. But I need that aech enumerator be awared of some type at compile-time.
Instead of just Class<?> you can use Class<? extends SomeClass>
Maybe I just didn't understand what you meant, but I think it doesn't provide compile-time type safety anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.