Can I use a class instance as an argument for a generic in java?

199 Views Asked by At

I am passing a class as a parameter to a method and I need to create an instance of that class, something like

public void setPiece(int i0, int j0, Class<Piece> pieceClass) {
        Piece p = null;
        try {
            Constructor<pieceClass> constructor = new Constructor<>(argTypes);
            p = constructor.newInstance(args);
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        // other stuff
    }

but it won't accept this syntax. The argument inside <> needs to be a class, not a class object, so I don't know what to do.

I have seen people use something like pieceClass.newInstance(); which looks like might work, but it is deprecated and IntelliJ recommends that Constructor class. I'm more so just curious if it's possible to pass this parameter class as an argument for the generic, I haven't been able to find anything online.

1

There are 1 best solutions below

1
rzwitserloot On

Ah, you've misread how to make Constructor instances. You can't new them up - you ask the Class for it. Looks like this:

try {
  Constructor<Piece> ctr = pieceClass.getConstructor(argTypes);
  p = constructor.newInstance(args);
} catch (InstantiationException | IllegalAccessException e) {
  throw new RuntimeException("uncaught", e);
}

NOTE: e.printStackTrace(); as sole line in a catch block is incredibly bad (the program continues running in a state that you clearly didnt expect and have no idea about. That's a really, really silly idea. Stop doing it, and fix your IDE so that it no longer fills this in for you. The catch block I wrote above is a fine default value for a catch block.