Java use values method of Enum Generic

Anakin001 :

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?

Michael :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114962&siteId=1