Java – Learn about generic methods in Java

Learn about generic methods in Java… here is a solution to the problem.

Learn about generic methods in Java

I’m trying to understand one of the methods I’m reading in an existing Android app. The declaration of the method is as follows:

protected <V, T extends Result> void postObject(final V input, final T result, final ConnectionTarget endpoint, final boolean restart, final int id, final LoaderProvider provider, final ServiceCallbacks<T> callbacks) {

I

just read about generics, so I more or less understand what’s going on here, but not completely. So I have two questions:

  1. Should input be a type (i.e. class), or should it just be an object of any type?
  2. What does <V, T extend Result> mean? As far as I know, that place should always describe the return type of the method, but it already says void after it, plus, it means both V and T

Can anyone give an example of how to call this method?

Solution

I’ll break it into smaller parts so it’s easier to understand.
In the section:

protected <V, T extends Result> void

<V, T extends Result> is an optional (usually nonexistent) section that specifies a generic type (or an unknown object type). This is specified by < and >, and any comma-separated values are a separate object (object “T” must extend the result).

This means later in the method call:

... postObject(final V input,...

The input is object type V, which means it can be any object you want.

Edit

A basic example of calling this method is:

//Now post it
postObject("my input object", null /*Your result class*/, null /*your endpoint*/, true, 0, null /*your loaderProvider*/, null /*your callbacks*/);

Related Problems and Solutions