【问题标题】:How to automatically insert a class notation using eclipse templates?如何使用 Eclipse 模板自动插入类符号?
【发布时间】:2011-02-09 17:06:12
【问题描述】:

有人知道如何使用 Eclipse 模板在类签名上方插入“@RunWith 注释”吗?

例如:

@RunWith(Parameterized.class)
public class MyClassTest {
...
    @Parameters
    public static Collection<Object[]> parameters() {
        List<Object[]> list = new ArrayList<Object[]>();
        list.add(new Object[] { "mind!", "find!" });
        list.add(new Object[] { "misunderstood", "understood" });
        return list;
    }
...
}

__

模板:

// TODO: move this '@RunWith(Parameterized.class)' to class anotation
    @Parameters
    public static Collection<Object[]> parameters() {
        ${type:elemType(collection)}<Object[]> parametersList = new ${type:elemType(collection)}<Object[]>();
        ${cursor}// TODO: populate collection
        return parametersList;
    }

__感谢您的帮助!

【问题讨论】:

    标签: java eclipse code-generation eclipse-templates


    【解决方案1】:

    不幸的是,您不能使用 Eclipse 模板向现有的封闭类添加注释(至少,我不知道)。但是,有一种解决方法。这是您的模板的修改版本:

    @${runnerType:newType(org.junit.runner.RunWith)}(${paramterizedType:newType(org.junit.runners.Parameterized)}.class)
    public class ${primary_type_name} {
        @${parametersType:newType(org.junit.runners.Parameterized.Parameters)}
        public static ${collectionType:newType(java.util.Collection)}<Object[]> parameters() {
            ${baseCollectionType}<Object[]> parametersList = new ${concreteCollectionType}<Object[]>();
            ${cursor}// TODO: populate collection
            return parametersList;
        }
    }
    

    使用模板(假设其名为“参数化”):

    1. 在 Eclipse 中创建一个新类
    2. 在执行任何其他操作之前,请选择存根类声明,包括左大括号和右大括号。
    3. 键入模板名称,然后按Cntrl+Space 激活模板(您可能必须从模板列表中选择模板。我只有一个名为Parameterized 的模板,所以Eclipse 自动为我使用它) .

    类定义将替换为包含@RunWith 注释的定义。我使用 ${id:newName(reference)} 模板变量使 Eclipse 自动添加所有必要的导入(${baseCollectionType} 的导入除外和${concreteCollectionType},你必须手动添加它们......感谢上帝Cntrl-Shift-M)

    这真的很难描述。您必须尝试一下才能确切了解它是如何工作的。如果我的指示需要澄清,请发表评论。

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 2013-10-20
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2019-07-29
      • 1970-01-01
      相关资源
      最近更新 更多