Look at this article: http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
Quoting from it directly:
There are two reflective methods for creating instances of classes: java.lang.reflect.Constructor.newInstance() and Class.newInstance(). The former is preferred and is thus used in these examples because:
- Class.newInstance() can only invoke the zero-argument constructor, while Constructor.newInstance() may invoke any constructor, regardless of the number of parameters.
- Class.newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor.newInstance() always wraps the thrown exception with an InvocationTargetException.
- Class.newInstance() requires that the constructor be visible; Constructor.newInstance() may invoke private constructors under certain circumstances.
Let me add some code for you. First of all, you need to get a reference to the class whose instance you want to create. You already have the name of the class, so do this:
Class pieceKlass = Class.forName(spawnPiece)
Then get its constructor which accepts a single string and create an instance of the class:
Constructor ctor = pieceKlass.getDeclaredConstructor(String.class);
ctor.setAccessible(true);
ChessPiece piece = (ChessPiece)ctor.newInstance(pieceRepresentation);
Given that this piece of code is pretty complex and needs some error handling as well, you can now extract it out in a factory class neatly:
class ChessPieceFactory {
public ChessPiece create(String pieceName, String pieceRepresentation) {
ChessPiece piece;
try {
Class pieceKlass = Class.forName(pieceName)
Constructor ctor = pieceKlass.getDeclaredConstructor(String.class);
ctor.setAccessible(true);
piece = (ChessPiece)ctor.newInstance(pieceRepresentation);
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
} catch (InstantiationException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
} catch (InvocationTargetException x) {
x.printStackTrace();
} catch (NoSuchMethodException x) {
x.printStackTrace();
}
return piece;
}
Since you have also tagged the question with the Chess tag, I should point out that you should use the standard Forsyth-Edwards Notation to populate the chess board. It uses upper case letters to denote white pieces and lower case letters to denote the black pieces.