Java: how does this code work (undefined return type)


In the sun extended RMI tutorial, they have some interesting code which implements a 'compute engine', using RMI they pass the function over to the compute engine, which then returns the results. More details here:

This means that at the onset the return type is not known, so they use the following work-around:

package compute;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Compute extends Remote {
    <T> T executeTask(Task<T> t) throws RemoteException;

and package compute;

public interface Task<T> {
    T execute();

how is this able to work? what property of java does implement? what could i read up more about this?


how does this code work (return type undefined)

This code is using generics, and the T is called a generic type parameter. The return type isn't really "undefined". Instead, we say it's parameterized: the return type will eventually be replaced by a real, concrete type. That is, the return type is defined by whatever kind of Task<T> you've created.

You can think of this like a function which accepts a particular type and generates a specialized version of each Task<T> that is requested. (That's not quite what happens under the covers -- in fact, ultimately the compiler discards the information about a generic object's runtime type -- but a more in-depth treatment is probably outside the scope of this StackOverflow answer.)

Under the covers, when you compile this code, the Java compiler will make sure that no rules are broken about the creation of Task<T>'s and the relationship to its execute() methods. For example, the compiler will flag this as illegal:

public class Boat { ... }
public class Car { ... }

public CarFactory implements Task<Car> {
  public Boat execute() { ... } // Error! A Boat is not a Car.