tags:

views:

99

answers:

2

Hello Everyone,

I am used to doing dynamic Binding in PHP this way

function ($className)
{
 $obj = new $className();
 .
 .
 .
}

here $className is a String parameter and based on name of the class an object of that class is created. So when I need to add more functionality I just add another class and everything get sorted out automatically.

Now I want to do something similar in Java. Right now my code is

public EditPart createEditPart(EditPart context, Object model) {

AbstractGraphicalEditPart part = null;

if(model instanceof Entreprise) {
part = new EntreprisePart();
else if(model instanceof Employee)
part = new EmployeePart();
.
.
.

}

My aim is that if I add a new Class to the package, I shouldn't have the need to modify my createEditPart function. How is it done in Java.

+3  A: 

One option is to create a factory that each of your classes can register themselves with and then can be called to create the appropriate object.

Amber
This was pretty much the solution I was looking for. I will post the code when done.
Chaitannya
A: 

One way to handle this, or at least to do the same thing you're talking about in the PHP, is reflection. You can obtain a Class object from a string specifying the fully-qualified class name, and use that class to create a new instance of itself dynamically.

public EditPart createEditPart(String name) throws [lots of stuff] {
    return Class.forName(name).asSubclass(EditPart.class).newInstance();
}

However, this is a relatively inefficient way to use Java, and I wouldn't necessarily recommend it. Some other languages use reflection quite liberally (like PHP), but not so much with Java. Amber's factory idea is a good one and if I were doing it, I might go with that.

If you want to create your EditPart based on the class of the model object (as in your code sample), rather than on the name of the EditPart subclass, then you can't use reflection. Well, you can, but you'll still need some way to tell the program which EditPart corresponds to which type of model. One option would be to change the type of the model parameter from Object to some interface, say EditModel, which you would write to have a method that returns an instance of the appropriate part. Like so:

public interface EditModel {
    public EditPart getEditPart();
}

Then you could just write your createEditPart as

public EditPart createEditPart(EditModel model) {
    return model.getEditPart();
}

(actually, if it's that simple you probably don't even need createEditPart at all). If you don't want to or can't do that, you could set up something with reflection that chooses the part class dynamically based on the name of the model class, but that really sounds unnecessarily complicated. At that point you'd definitely be better off going with the factory pattern.

David Zaslavsky