---
title: "Java generic methond without any parameters"
author: "jusi"
date: "2014-12-15T10:34:25Z"
tags: []
categories: ["编程语言"]
slug: "java-generic-methond-without-any-parameters"
draft: false
lastmod: "2014-12-15T10:34:25Z"
id: 2166297
url: "https://jusi.iteye.com/blog/2166297"
---

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();
```