简体   繁体   English

在使用Java编译时生成代码?

[英]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. 我创建了一组代表RESTful资源的类,以及实际上执行HTTP请求以检索和构建对象的其他帮助程序。 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. 现在碰巧,我想使用POJO类以便插入喜欢处理POJO的框架。

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. 这取决于您构建的系统是什么,如果您是javac ,那么我会拒绝,但是如果您使用antmaven则可以。

There are lots of examples for code generators. 有很多示例代码生成器。

In your case I would use reflection on the compiled MyResource class. 在您的情况下,我将对已编译的MyResource类使用反射。 I would consider using Velocity to help template the class. 我会考虑使用Velocity帮助模板制作类。 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 DI的基本示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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