例如,我有这样的JSON:
{
"extends": "core-range",
"dependencies": [
"paper-progress",
"paper-input"
],
"jsdoc": [
{
"description": "Fired when the slider's value changes.",
"kind": "event",
"name": "core-change",
"longname": "event:core-change"
},
{
"name": "snaps",
"kind": "member",
"longname": "snaps",
"scope": "global"
},
{
"name": "pin",
"kind": "member",
"longname": "pin",
"scope": "global"
},
{
"name": "disabled",
"kind": "member",
"longname": "disabled",
"scope": "global"
}
]
}
我需要生成这样的Java类:
import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;
import com.google.gwt.user.client.EventListener;
@JsType(prototype = "HTMLElement", isNative = true)
public interface PaperSlider extends HTMLElement , CoreRange {
Class<?>[] dependencies = new Class<?>[]{PaperProgress.class, PaperInput.class};
void addEventListener(String event, EventListener listener);
@JsProperty PaperSlider snaps(boolean val);
@JsProperty boolean snaps();
@JsProperty PaperSlider pin(boolean val);
@JsProperty boolean pin();
@JsProperty PaperSlider disabled(boolean val);
@JsProperty boolean disabled();
}
生成它的最佳方法是什么?可能使用模板是有意义的。最困难的部分是方法生成。
我没有找到任何支持可重复模板的Node.js模块。
顺便说一句,我有很多JSON文件,我将把它添加到我的Gulp任务中以生成一些源文件。答案 0 :(得分:3)
有几种方法可以解决这个问题。我建议通过grunt来完成。
全局安装grunt:
npm install grunt-cli -g
然后安装本地grunt(在当前目录中):
npm install grunt
创建模板(class.tmpl):
import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;
import com.google.gwt.user.client.EventListener;
@JsType(prototype = "HTMLElement", isNative = true)
public interface PaperSlider extends HTMLElement , CoreRange {
Class<<%= className %>>[] dependencies = new Class<<%= className %>>[]{PaperProgress.class, PaperInput.class};
void addEventListener(String event, EventListener listener);
<% _.forEach(methods,function(method){ %>
<%= method.description && ("// " + method.description) %>
@JsProperty PaperSlider <%= method.name %>(boolean val);
@JsProperty boolean <%= method.name %>();
<% }) %>
}
最后创建Gruntfile.js
:
// config is your JSON file
// Yes, you can require json files
var config = require("./config");
module.exports = function(grunt) {
grunt.registerTask("makeClass",function() {
var template = grunt.file.read("./class.tmpl");
var fileData = grunt.template.process(template,{
data: {
methods: config.jsdoc,
className: "JSClass"
}
});
grunt.file.write("./class.java", fileData);
})
grunt.registerTask('default', ["makeClass"]);
};
现在只需运行grunt
。