0

I am unable to find out how to do this. I am being told that a type and a class are two different things, which I didn't know, but doesn't suprise me. When I use the type varriable 'M', I am told that it was expecting a class, not a type. I am willing to take in parameters in any way. Also, if there is a way to get an array of these classes, that would be the best.

public <M> void addModule()
{
  Module module = new M(); // This is the error, other stuff shouldn't matter
  module.setStructure(this);
  modules.add(module);
}
  • See https://stackoverflow.com/questions/16600750/difference-between-class-and-type for the distinction – sprinter Nov 26 '19 at 04:12

1 Answers1

0

A type variable (such as M in your example) is a placeholder for a real type. The real type is determined at runtime. In your code it is impossible for the compiler to know how to create a M because it doesn't know what it is.

You likely need something like this:

interface Module {
    void setStructure(ModuleCollection collection);
}

interface ModuleMaker<T extends Module> {
    T makeModule();
}

class ModuleCollection {
    private final List<Module> modules = new ArrayList<>();

    public void addModule(ModuleMaker<?> maker) {
        Module module = maker.makeModule();
        module.setStructure(this);
        modules.add(module);
    }
}
sprinter
  • 27,148
  • 6
  • 47
  • 78