【问题标题】:Configure Xtext generator at runtime在运行时配置 Xtext 生成器
【发布时间】:2019-02-17 11:34:44
【问题描述】:

我已经用 Xtext 实现了 DSL,我正在尝试找到一种方法来动态配置 mydsl.ui Eclipse 插件中的代码生成。

为了配置生成器,我引入了一个偏好参数。

我用 MyDslRuntimeModule 注入了一个自定义的 GeneratorConfiguration 对象

然后我在自定义BuilderParticipant(在plugin.xml中配置)的“build”方法中设置这个对象的preference参数。

// In mydsl plugin    
class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {

    def Class<? extends IGeneratorConfiguration> bindIGeneratorConfiguration() {
        return GeneratorConfiguration;
   }

}

// In mydsl.ui plugin
package mydsl.ui;

public class MyBuildPartecipant extends BuilderParticipant {

@Inject IGeneratorConfiguration generatorConfiguration;

@Override
public void build(IBuildContext context, IProgressMonitor monitor) throws CoreException {

    ScopedPreferenceStore scopedPreferenceStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, "ID");

    generatorConfiguration.setGeneratorProperty(scopedPreferenceStore.getInt("myDslProperty"));

    super.build(context, monitor);
}

// In mydsl plugin
class MyDslGenerator extends AbstractGenerator {

@Inject IGeneratorConfiguration generatorConfiguration;

    override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {

        println("Compiling with " + generatorConfiguration.generatorProperty)  

结果是mydsl.ui插件(eclipse ui)的MyBuildPartecipant类中@Inject装饰器获取的GeneratorConfiguration对象与mydsl插件(Xtext生成器插件)的MyDslGenerator类中获取的GeneratorConfiguration对象不同。

如何将 eclipse ui 插件中的参数传递给 Xtext 生成器插件(非 ui 插件)以动态配置代码生成?

谢谢 保罗

【问题讨论】:

    标签: eclipse generator xtext inject preference


    【解决方案1】:

    我解决了:

    // In mydsl plugin    
    class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {
    
        def IGeneratorConfiguration bindIGeneratorConfiguration() {
            return new GeneratorConfiguration();
       }
    

    【讨论】:

      【解决方案2】:

      您应该用@Singleton 标记GeneratorConfiguration 类。

      或使用配置方法添加单例绑定

      def void configureIGeneratorConfiguration(Binder binder) {
          binder.bind(IGeneratorConfiguration).to(GeneratorConfiguration).in(Scopes.SINGLETON)
      } 
      

      或用@SingletonBinding注释类绑定

      @SingletonBinding
      def Class<? extends IGeneratorConfiguration> bindIGeneratorConfiguration() {
          GeneratorConfiguration
      }
      

      如果你将东西注入到 GeneratorConfiguration 类中,你的做法将无法正常工作

      【讨论】:

      • 感谢您对 Xtext 的支持和贡献。我的错误来自 AbstractMyDslRuntimeModule 的副本,public Class&lt;? extends IGenerator2&gt; bindIGenerator2() { return MyDslGenerator.class; } 的行为就像一个单身人士。
      • 实际上没有。生成器只有一个地方被创建,所以它是“一个实例”,而不是一个单例
      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      相关资源
      最近更新 更多