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.
Ah, you've misread how to make Constructor instances. You can't
newthem up - you ask the Class for it. Looks like this: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.