简体   繁体   中英

Generate code at compile time with Java?

I've created a set of classes that represent RESTful resources, and other helper things that actually do the HTTP requests to retrieve and build objects. My classes look like this :

class MyResource{
    Attribute id = new Attribute(this, long);
    Attribute name = new Attribute(this, String);
    /* etc */
}

Now it happens that I would like to use POJO classes in order to plug to a framework that likes to deal with POJOs.

I would like to have proxies that would look like this:

class MyResourceProxy{
    private MyResource realResource;

    public MyResourceProxy(MyResource o){realResource = o;}

    public long getId(){
        return realResource.id.get();
    }

    public void setId(long value){
        realResource.id.set(value);
    }

    public String getName(){
        return realResource.name.get();
    }

    public void setName(String value){
        realResource.name.set(value);
    }        
}

I don't want to have to maintain code for those proxy classes, but only the "resource-type" master classes.

I looked into introspection and found a hint on how to generate the said proxy code on demand. The question is : is it possible to generate the code at compile-time, and then have it compiled along with the library? Maybe I've taken the wrong turn and I'm doing something uninteresting, though ;)

What do you think? Thanks!

It depends on what you build system is, if you mean javac , then I would say no, but if you use ant or maven then you can.

There are lots of examples for code generators.

In your case I would use reflection on the compiled MyResource class. I would consider using Velocity to help template the class. It may be overkill in your case, but as you generate more code it may be useful.

Have you tried using dependency injection to generate your classes on instantiation?

Basic example for DI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM