I don't think Java can infer a second generic type without any hint. One way is to specify the type of variable declaration:
TestBuilder<String, String> testBuilder = new TestBuilder<>(String.class); testBuilder.withOnNext(new Action1<String>() { @Override public void call(String string) {
But you still need to declare both common parameters.
What I would do is encapsulate the information that both the T and O methods are the same in the static factory method:
public class TestBuilder<T, O> { public static <T> TestBuilder<T, T> create(Class<T> eventClass) { return new TestBuilder<T, T>(eventClass); } // ... }
and then call it like this:
TestBuilder.create(String.class).withOnNext(...);
Another option is to encapsulate information in a separate class that inherits from TestBuilder :
public class SimpleTestBuilder<T> extends TestBuilder<T,T> { public SimpleTestBuilder(Class<T> eventClass) { super(eventClass, eventClass); } } public class TestBuilder<T, O> { private TestBuilder(Class<T> eventClass, Class<O> observableClass) { } // ... }
Used as
new SimpleTestBuilder<>(String.class).withOnNext(...);
Another good option is to encapsulate O information in a static method:
public class TestBuilder<T, O> { public static <T> TestBuilder<T, T> create(Class<T> eventClass) { return new TestBuilder<T, T>(eventClass); } // ... }
Used as
TestBuilder.create(String.class).withOnNext(...);