在基于Xtend的Xtext代码生成器中使用Inject

时间:2018-07-19 20:43:34

标签: xtext

我是Xtext和Xtend的新手,正尝试使用Xtext文档中的Xtext教程学习Xtext。我正在Xtext 2.14下在Java 10下的Eclipse Photon上运行。我正在开始扩展教程,并且很早就遇到了问题。这是我尝试使用代码生成器的代码:

/*
 * generated by Xtext 2.14.0
 */
package net.wiseoldbird.tutorial.domainmodel.generator

import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.xtext.generator.AbstractGenerator
import org.eclipse.xtext.generator.IFileSystemAccess2
import org.eclipse.xtext.generator.IGeneratorContext
import net.wiseoldbird.tutorial.domainmodel.domainmodel.Entity
import com.google.inject.Inject

@Inject extension IQualifiedNameProvider;

class DomainmodelGenerator extends AbstractGenerator {

    override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
        for (e: resource.allContents.toIterable.filter(Entity)) {
        fsa.generateFile(e.fullyQualifiedName.toString("/") + ".java", e.compile)

        }
    }
}

这是我的语法文件:

grammar net.wiseoldbird.tutorial.domainmodel.Domainmodel
        with org.eclipse.xtext.common.Terminals

generate domainmodel "http://www.wiseoldbird.net/tutorial/domainmodel/Domainmodel"

Domainmodel :
    (elements+=AbstractElement)*;

PackageDeclaration:
    'package' name=QualifiedName '{'
        (elements+=AbstractElement)*
    '}';

AbstractElement:
    PackageDeclaration | Type | Import;

QualifiedName:
    ID ('.' ID)*;

Import:
    'import' importedNamespace=QualifiedNameWithWildcard;

QualifiedNameWithWildcard:
    QualifiedName '.*'?;

Type:
    DataType | Entity;

DataType:
    'datatype' name=ID;

Entity:
    'entity' name=ID ('extends' superType=[Entity|QualifiedName])? '{'
        (features+=Feature)*
    '}';

Feature:
    (many?='many')? name=ID ':' type=[Type|QualifiedName];

我的问题是Eclipse表示@Inject批注存在问题。它说Inject cannot be resolved to an annotation type。这是根据教程中的说明生成的Eclipse Xtext项目中。

如何从这里继续?

1 个答案:

答案 0 :(得分:1)

您只能注入字段和后初始化方法/构造函数参数

import com.google.inject.Inject
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.xtext.example.domainmodel.domainmodel.Entity
import org.eclipse.xtext.generator.AbstractGenerator
import org.eclipse.xtext.generator.IFileSystemAccess2
import org.eclipse.xtext.generator.IGeneratorContext
import org.eclipse.xtext.naming.IQualifiedNameProvider

class DomainmodelGenerator extends AbstractGenerator {

    @Inject extension IQualifiedNameProvider

    override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
        for (e : resource.allContents.toIterable.filter(Entity)) {
            fsa.generateFile(e.fullyQualifiedName.toString("/") + ".java", e.compile)

        }
    }

    def compile(Entity e) '''
        package «e.eContainer.fullyQualifiedName»;

        public class «e.name» {
        }
    '''
}