我收到一个编译错误。我希望我的静态方法在这里返回一个工厂,它创建并返回Event<T>对象。我怎么才能解决这个问题?
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>();
}
};
}发布于 2014-03-29 04:40:48
类的泛型参数不适用于静态成员。
显而易见的解决办法是使用一种方法,而不是变量。
public static <U> EventFactory<Event<U>> factory() {
return new EventFactory<Event<U>>() {
public Event<U> newInstance() {
return new Event<U>();
}
};
}在当前版本的Java中,语法更加简洁。
可以使用存储在静态字段中的相同的EventFactory实例,但这需要不安全的转换。
发布于 2014-03-29 04:41:32
你有:
public final class Event<T> {
...
public final static EventFactory<Event<T>> EVENT_FACTORY = ...
}你不能这么做。T是一种与Event<T>的特定实例相关联的类型,您不能在静态上下文中使用它。
如果不知道您到底想做什么,就很难给出好的备选方案,因为这是一个看起来有点奇怪的工厂实现。我想您可以这样做(将其放在一个方法中):
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>();
}
};
};
}并引用它,就像:
EventFactory<Event<Integer>> factory = Event.<Integer>createEventFactory();或者,如果您不想显式(您不需要这样做,在这里):
EventFactory<Event<Integer>> factory = Event.createEventFactory();为什么你不把Event的静态成员全部去掉,或者把工厂分开,例如:
public final class GenericEventFactory<T> extends EventFactory<Event<T>> {
@Override public Event<T> newInstance() {
return new Event<T>();
}
}并在适当的地方使用,例如new GenericEventFactory<Integer>()?
https://stackoverflow.com/questions/22726946
复制相似问题