Yogesh Pitale
Yogesh Pitale

Reputation: 165

Using generics in java ENUM

This is how I have written my enum.

public enum JobClass {

    START_STOP(SchedularEvent<ExceptionNotificationsJob>.class),
    EMAIL_NOTIFICATION(SchedularEvent<GenericNotificationsJob>.class);

    private Class clazz; 

    JobClass(Class<?> clazz) {
        this.clazz = clazz;
    }

    public Class getClazz() {
        return this.clazz;
    }

}

However this does not compile! It throws following errors.

Multiple markers at this line

I am not sure how I should write this.

My aim is to get SchedularEvent<ExceptionNotificationsJob>.class when I call JobClass.START_STOP.getClazz(). How do I achieve this?

Thanks in advance!

Upvotes: 1

Views: 71

Answers (1)

MC Emperor
MC Emperor

Reputation: 22977

You cannot do that like this. SchedularEvent<GenericNotificationsJob>.class is not valid, because generics are erased at runtime, it only provides compile-time safety.

How you would have to rewrite the code depends on what exactly it is you want to achieve. One thing you can do is just SchedularEvent.class. You could also use Reflection to get the class of the containing type of your SchedularEvent, but that is generally not a good idea.


Also, you shouldn't use raw types. Replace Class clazz by Class<?> clazz.

Upvotes: 1

Related Questions