Roy
Roy

Reputation: 569

Generic static factory

I am getting a compilation error. I want my static method here to return a factory that creates and return Event<T> object. How can I fix this?

import com.lmax.disruptor.EventFactory;

public final class Event<T> {

    private T event;

    public T getEvent() {

        return event;
    }

    public void setEvent(final T event) {

        this.event = event;
    }

    public final static EventFactory<Event<T>> EVENT_FACTORY = new EventFactory<Event<T>>() {

        public Event<T> newInstance() {

            return new Event<T>();
        }


     };

}

Upvotes: 0

Views: 141

Answers (2)

Jason C
Jason C

Reputation: 40335

You have:

public final class Event<T> {
    ...
    public final static EventFactory<Event<T>> EVENT_FACTORY = ...
}

You cannot do this. T is a type that is associated with a specific instance of an Event<T>, and you cannot use it in a static context.

It's hard to give you good alternate options without knowing more about what exactly you are trying to do, as this is sort of an odd-looking factory implementation. I suppose you could do something like (put it in a method instead):

public final class Event<T> {
    ...
    public static <U> EventFactory<Event<U>> createEventFactory () { 
        return new EventFactory<Event<U>>() {
            public Event<U> newInstance() {
                return new Event<U>();
            }
        };
    };
}

And invoke it like:

EventFactory<Event<Integer>> factory = Event.<Integer>createEventFactory();

Or, if you don't want to be explicit (you don't really need to be, here):

EventFactory<Event<Integer>> factory = Event.createEventFactory();

Why don't you get rid of the whole static member of Event thing and either keep the factories separate, e.g.:

public final class GenericEventFactory<T> extends EventFactory<Event<T>> {
    @Override public Event<T> newInstance() {
        return new Event<T>();
    }
}

And use, e.g., new GenericEventFactory<Integer>() where appropriate?

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Generic parameters of a class do not apply to static members.

The obvious solution is to use a method rather than a variable.

public static <U> EventFactory<Event<U>> factory() {
    return new EventFactory<Event<U>>() {
        public Event<U> newInstance() {
            return new Event<U>();
        }
    };
}

The syntax is more concise in the current version of Java.

It is possible to use a the same instance of EventFactory stored in a static field, but that requires an unsafe cast.

Upvotes: 3

Related Questions