class PieceFactory {
@SuppressWarnings("rawtypes")
public Piece createPiece(String pieceType) throws Throwable{
Class pieceClass = Class.forName(pieceType);
Piece piece = (Piece) pieceClass.newInstance();
return piece;
}
}
I'm not all used to handling exceptions yet therefore I'm just throwing them, but everywhere I use a method that uses this factory it tells me I have to throw exceptions like throwable.
For example, in one of my classes I have a method that instantiates a lot of objects using the method that uses the factory. I can use the method in that class by just throwing the exception, however it won't work if I try to pass a reference to that class to another class and then use the method from there. Then it forces me to try catch the exception.
I probably don't need a factory but it seemed interesting and I'd like to try to use patterns. The reason I created the factory was that I have 6 subclasses of Piece and I wan't to use a method to instantiate them by passing the type of subclass I want as an argument to the method.
You are trying to reflectively create a Piece
object.
Class.forName()
throws ClassNotFoundException
, while Class.newInstance()
throws InstantiationException, IllegalAccessException (hence why you need to throw Throwable
.
A better way to create an object through class types is probably by doing the following:
class PieceFactory {
public Piece createPiece(String pieceType) throws Throwable{
Piece piece = null;
if ("SubPiece1".equals(pieceType)) {
piece = new SubPiece1();
} else if ("SubPiece2".equals(pieceType)) {
piece = new SubPiece2();
}
return piece;
}
}
PS, it's untested, just showing a better way to do it.
Hope this helps! :)