Auto Generation Objects

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

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, 
}

Class variables must be obtained from the getter methods of the interface. In the ideal case, covariant return types in interfaces will be processed. Implementation should promote immutability using private final variables and an instance of the constructor. Equals, hashCode, and toString methods must be created.

+3
source share
4 answers

A cleaner way uses CGLIB to dynamically create a class at runtime. Obviously, you cannot view the source file.

, codemodel - :

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"));

, , IDE ( Eclipse: Menu "Source", "Generate hashcode() equals()...", ..)

+3

, eclipse .

get, getter . , equals, hashcode toString.

, , .

+1

, , javac (apt Java SE 1.5).

+1
source

In addition, using the modern Java IDE, which will help you in coding, you can also check using a dynamic proxy

0
source

Source: https://habr.com/ru/post/1706371/


All Articles