简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM