Generic types in Java method call

Asked

Viewed 113 times

4

I wanted to understand how this works and the name they give it in Java.

Follow the code snippet:

public <I, O> SimpleStepBuilder<I, O> chunk(int chunkSize) {
    return new SimpleStepBuilder<I, O>(this).chunk(chunkSize);
}

The doubt relates to this first <I, O>, I was confused if this would be the kind of feedback, but testing a little the kind of feedback is SimpleStepBuilder<I, O>, which got me confused.

Source code: spring-Projects/spring-batch

2 answers

4


The term could be generic parameterization.

This is the moment that is defined which generic terms will be used in the composition of the method, this is where generic parameters are being defined (not to be confused with parameters of the method itself). Remember that genericity is just a way to parameterize something, so there is something that works as super variables in the code that will be exchanged for the value (a type) at the time of the call. This part defines what will be used.

In fact you are correct that the type of return is already the SimpleStepBuilder<I, O> who uses the I and O to generalize the type that will be effectively used in the method call (instantiating that class SimpleStepBuilder parameterizing two types in it. This part consumes the definition created before.

In general it is easier for the compiler to know the definition before, but it is less intuitive to read because in consumption the generic argument will be elsewhere.

In C# it would be more intuitive:

public SimpleStepBuilder<I, O> chunk<I, O>(int chunkSize) => new SimpleStepBuilder<I, O>(this).chunk(chunkSize);

I put in the Github for future reference.

4

As said in reply previous, the term could be generic parameterization.

The <I, O> in the signature means that the method can handle these two generic types, this is not the return. For example, you could have a method with no return and with this signature.

 public static <I, O> void test(I i, O o){
    System.out.println(i);
    System.out.println(o);
}

In your case, the return of the method is the SimpleStepBuilder<I, O>

  • That term is for something else.

  • 1

    There is no easy and well-defined term about it, but I put in my answer what it is, the one you put has to do with the subject, but it is for something far more sophisticated than that, this code has no restriction (bounded).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.