Anakin001
Anakin001

Reputation: 1256

Java use values method of Enum Generic

I want to parameterize a class with an enum, then in the constructor of the class create an Array having the size of the number of elements in the enum.

I created the class like this:

public class LogLine <T extends Enum<T>> {

And then in the constructor I tried writing this:

public LogLine(){
numberOfElementsInEnum = T.values().length;
//then I would create the Array based on the numberOfElementsInEnum variable

It doesn't work. The compiler doesn't see the values method. I tried with T extending String instead of Enum. All static method are then accessible. What is the issue here?

Upvotes: 3

Views: 884

Answers (2)

Michael
Michael

Reputation: 44150

You don't strictly "have to" pass the class to the constructor. In some cases this is a needless inconvenience for the person instantiating your class.

It all depends on your interface.

If your interface is purely a consumer of items (and given that you're logging, I suspect it might be), then you can get away with lazily calculating the number of values at the point when you're actually consuming the item.

class LogLine<T extends Enum<T>>
{
    public void add(T item)
    {
        int numberOfElementsInEnum = item.getDeclaringClass().getEnumConstants().length;
    }
}

We would need know your requirements and to see the rest of your implementation of LogLine to say whether this approach is suitable.

Upvotes: 3

keuleJ
keuleJ

Reputation: 3486

You have to declare a constructor that accepts the Class:

public LogLine(Class<T> c) {
    numberOfElementsInEnum = c.getEnumConstants().length;
}

See also here: https://docs.oracle.com/javase/tutorial/reflect/special/enumMembers.html

Upvotes: 5

Related Questions