ITeye博客

Java generic methond without any parameters

jusi · 2014-12-15 10:34 · java · 编程语言 · Markdown

Regarding following class: We define a generic class, but we donot have a method to resolve the generic.

public final class Event<T> {

    private T event;


    private Event() {}


    public T getEvent() {
        return event;
    }

    public static <T> Builder<T> newBuilder() {
        return new Builder<>();
    }

    public static final class Builder<T> {
        private Builder() {}

        private final Event<T> instance = new Event<>();

        public final Builder<T> event(T event) {
            instance.event = event;
            return this;
        }

        public final Event<T> build() {
            return instance;
        }
    }
}

 

 

 If we create an event like this, we always get an Object instance instead of String.

Event<Object> o = Event.newBuilder().event("String").build();

 

 

We should pass the type explicitly.

 

Event<String> s = Event.<String>newBuilder().event("String").build();

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。