Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autogenerate value objects

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.

like image 864
parkr Avatar asked Dec 05 '25 15:12

parkr


2 Answers

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.)

like image 98
Daniel Fanjul Avatar answered Dec 08 '25 03:12

Daniel Fanjul


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.

like image 25
Bhushan Bhangale Avatar answered Dec 08 '25 03:12

Bhushan Bhangale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!