0

我需要生成 java 模板代码来访问具有结构的嵌套对象。

例如:

class Person{
    private String name;
    private List<Address> address;

}

class Address{
    private String doorNo;
    private String Address;
    private City city;
}

class City{
    ....
}

因此,需要一个方法来获取任何对象(嵌套)并为上述人员对象生成 java 代码,如下所示。

//Generated java code should be like this
if(person != null){
    String name = StringUtils.isEmpty(Person.getName());
    if(person.getAdressList() != null && person.getAddressLit().isNotEmpty()){

        for (Address address : person.getAdressList()) {
            ......
        }
    }
}

该方法应该是通用的并且为动态嵌套对象递归地生成代码。

非常感谢您的帮助。谢谢。

4

2 回答 2

2

代码生成是一项复杂的任务,在 StackOverflow 的问答格式中无法完全回答。

请记住,在编写“仅”创建您在此处描述的方法的函数时,大约需要一天左右的时间。也许手写虽然很无聊,但却是更省时的方法。( http://xkcd.com/1205/ )

If you want to generate code you first have to pick a code generation tool that does what you need. There are several (maybe you can use the refactoring functions of your IDE as well). If you want to be able to manipulate the way the code is processed within the original source code, I have found the Java APT to be very useful. It will let you traverse packages of Java code and generate classes and methods according to the structure found therein. It is a tool that can interpret Annotations to be able to determinate what to do with any single method.

于 2013-09-30T09:42:16.720 回答
0

Consider using JetBrains MPS. That's a metaprogramming IDE with Java as a first-class target. http://www.jetbrains.com/mps/

Another approach would be to develop a Spring Roo plugin. http://projects.spring.io/spring-roo/

于 2013-10-28T14:00:00.887 回答