Java Generics Hell - Pass in this, but he wants type T

I am currently developing a lightweight universal simulation. The goal is to allow people to subclass modeling and scenario objects for their domain-specific needs. Generics seemed like the right way to achieve this, but I'm afraid that I might be immersed in generic hell.

The object Simprovides access to simulation entities and controls the sim (start / pause / stop)

An object Scenarioallows you to populate Sim with simulation objects.

Sim:

public class Sim 
{
  public <T extends Sim> void loadScenario(Scenario<T> scenario)
  {
      reset();
      scenario.load(this);
  }
}

Scenario:

public interface Scenario<T extends Sim>
{
    public void load(T sim);
}

The goal is to allow users to create MySimwhich extends Simand MyScenariowhich implements Scenario<MySim>for their domain.

eg. MyScenario:

public class MyScenario<MySim>
{
    public void load(MySim sim)
    {
        // make calls to sim.addMySimEntity(...)
    }
}

, , scenario.load(this) Sim.loadScenario : (T) (Sim), , , this ( Sim), T extends Sim, , , Sim.

, ? ? , .

+5
2

Sim, , ? , .

, , loadScenario :

public void loadScenario(Scenario<? extends Sim> scenario)

EDIT: , , . loadScenario T, Sim. Sim, , Sim.

, Scenario.load Sim:

public interface Scenario<T extends Sim>
{
    public void load(Sim sim);
}

, . , MySim .

EDIT: - Sim:

public class Sim
{
    public static <T extends Sim> void loadScenario(Scenario<T> scenario, T sim)
    {
        scenario.load(sim);
    }
}

, Sim T extends Sim . , Sim, , T T sim.

+6

, , ( Sim) T Sim - , Sim.

. , T, Sim, , - this ( , ).

, .

+2

All Articles