views:

200

answers:

4

Given an interface or interfaces, what is the best way to generate an class implementation?

interface Vehicle
{
    Engine getEngine();
}

@Generated
class Car implements Vehicle
{
    private final Engine engine;

    public Car(Engine engine)
    {
        this.engine = engine;
    }

    public Engine getEngine()
    {
        return engine;
    }

    // generated implementation of equals, hashCode, toString, 
}

The class variables should be derived from the getter methods of the interface. Ideally, covariant return types in the interfaces would be handled. The implementation should favour immutability by using private final variables and constructor instantiation. The equals, hashCode and toString methods should be generated.

+1  A: 

Do just like eclipse do when implementing a class for an interface.

If a method starts with get then consider that as a getter and parse the method to extract variable name and its type. Create a constructor for those fields as well and also implement equals, hashcode and toString methods.

You can do normal file parsing or maybe reflection can also help not sure.

Bhushan
A: 

besides using a modern java IDE that helps you in boilerplate coding you can also check using a dynamic Proxy

dfa
+1  A: 

If you are going to be doing it an awful lot, then you may wish to consider the annotation processor feature built in to javac (apt back in Java SE 1.5).

Tom Hawtin - tackline
+2  A: 

The cleaner way is using CGLIB to generate dynamically the class at runtime. Obviously, you are not able to browse the source file.

If you need the source file, you could try codemodel and do something like:

JCodeModel cm = new JCodeModel();
x = cm._class("foo.bar.Car");
x.field(Engine.class, "engine");
for (PropertyDescriptor pd:    Introspector.
              getBeanInfo(Vehicle.class).getPropertyDescriptors()) {
    g = x.method(JMod.PUBLIC, cm.VOID, pd.getReaderMethod().getName()); 
    g.body()...
    s = x.method(JMod.PUBLIC, cm.VOID, "set" + pd.getName());
    s.body()...
}
hc = x.method(JMod.PUBLIC, cm.VOID, "hashCode"));
hc.body()...
cm.build(new File("target/generated-sources"));

Or as suggested previously, use the IDE (in Eclipse: Menu "Source", "Generate hashcode() and equals()...", i.e.)

Banengusk
I will try JCodeModel. Thanks!
parkr