Re: Class.forName {creating objects on the fly}
gaurav.v.bagga@gmail.com wrote:
Hi All,
Just wanted to know creating instance
Class classDefinition = Class.forName("java.awt.Rectangle");
object = classDefinition.newInstance();
Is this a heavy process in terms of resources and its execution time?
regards
gaurav
Look into the Factory object pattern.
Using reflection is very limited...:
public Shape getShapeObject(String shapeClassName) throws Exception {
Class<? extends Shape> classDefinition =
(Class<? extends Shape>)Class.forName(shapeClassName);
return classDefinition.newInstance():
}
getShape("java.awt.Rectangle");
Using the factory object pattern:
public Shape getShapeObject(ShapeFactory shape) {
return shapeFactory.createShape();
}
getShape(new ShapeFactory() {
public Shape createShape() {
return new Rectangle();
}
}
public interface ShapeFactory {
Shape createShape();
}
Sure it looks like more code, but two important things to remember.
First, you won't need to worry so much about class names being wrong,
its checked by the compiler for you. Second, you have a much more
flexible way to get Shapes. If you need to pass in more values to the
constructor, you just do so in the factory.