Olivier H
Olivier H

Reputation: 898

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!

Upvotes: 1

Views: 1551

Answers (2)

Jason Brant
Jason Brant

Reputation: 182

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

Basic example for DI

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

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.

Upvotes: 2

Related Questions