Как добавить плагин xjc программно во время выполнения?
Я генерирую классы JAXB из xsd во время выполнения, используя XJC. Но по умолчанию maxLength
ограничение в xsd не аннотировано.
Я нашел плагин для решения этой проблемы, krasa-jaxb-tools. Я добавил зависимости в свой POM, но не могу добавить плагин в процесс XJC.
Я использую версию 2.2.11 инструментов jaxb-xjc. Вот мои зависимости:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-jxc</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.github.krasa</groupId>
<artifactId>krasa-jaxb-tools</artifactId>
<version>1.3</version>
</dependency>
Я пытаюсь создать экземпляр плагина, настроить его и передать его generateCode(Plugins[] extensions, ErrorListener errorListener)
метод на моем S2JJAXBModel
модель, но это, кажется, не имеет никакого эффекта. Вот мой код:
SchemaCompiler schemaCompiler = XJC.createSchemaCompiler();
schemaCompiler.forcePackageName(packageRoot);
// JAXB Plugin used to get the proper @Size annotations on all fields.
JaxbValidationsPlugins jaxbValidationPlugin = new JaxbValidationsPlugins();
// Build up list of options for the plugin.
// First option must be the name of the plugin itself.
// Options must be prefixed with dashes
String[] args = new String[] { "-" + JaxbValidationsPlugins.PLUGIN_OPTION_NAME };
try {
// Activate plugin
jaxbValidationPlugin.parseArgument(new Options(), args, 0);
} catch (BadCommandLineException | IOException e1) {
e1.printStackTrace();
}
InputSource inputSource = new InputSource(schemaFile.toURI().toString());
schemaCompiler.parseSchema(inputSource);
S2JJAXBModel model = schemaCompiler.bind();
// Passing the plugin to the method
JCodeModel jCodeModel = model.generateCode(new Plugin[] {jaxbValidationPlugin}, null);
Что я делаю неправильно?
1 ответ
Вот как фактическая реализация #generateCode()
метод выглядит в версии 2.2.11
// com.sun.tools.xjc.api.impl.s2j.JAXBModelImpl.java
public JCodeModel generateCode(Plugin[] extensions,ErrorListener errorListener) {
// we no longer do any code generation
return outline.getCodeModel();
}
Как видите, параметры просто проглатываются.
Чтобы добавить плагин, вы хотите получить доступ к Options
найдено в SchemaCompiler
и добавьте туда свой плагин. Обратите внимание также, что parseArgument()
Звонить следует по опциям, а не по плагину.
Вот как вы это делаете:
SchemaCompiler schemaCompiler = XJC.createSchemaCompiler();
schemaCompiler.forcePackageName(packageRoot);
// JAXB Plugin used to get the proper @Size annotations on all fields.
JaxbValidationsPlugins jaxbValidationPlugin = new JaxbValidationsPlugins();
// Build up list of options for the plugin.
// First option must be the name of the plugin itself.
// Options must be prefixed with dashes
String[] args = new String[] { "-" + JaxbValidationsPlugins.PLUGIN_OPTION_NAME };
// Get the options for the schema compiler, this is where we add plugins.
Options schemaCompilerOptions = ((SchemaCompilerImpl) schemaCompiler).getOptions();
schemaCompilerOptions.getAllPlugins().add(jaxbValidationPlugin);
// Call the parseArgument method on the options, not the plugin
// Passing in zero because we want to parse the first argument in the array
try {
schemaCompilerOptions.parseArgument(args, 0);
} catch (BadCommandLineException e1) {
e1.printStackTrace();
}
InputSource inputSource = new InputSource(schemaFile.toURI().toString());
schemaCompiler.parseSchema(inputSource);
S2JJAXBModel model = schemaCompiler.bind();
JCodeModel jCodeModel = model.generateCode(null, null);