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
Pieceobject.Class.forName()throwsClassNotFoundException, whileClass.newInstance()throws InstantiationException, IllegalAccessException (hence why you need to throwThrowable.A better way to create an object through class types is probably by doing the following:
PS, it’s untested, just showing a better way to do it.
Hope this helps! 🙂