【问题标题】:Is there a way to capitalize the first letter of a value of a variable in Eclipse (Helios) code templates有没有办法在 Eclipse (Helios) 代码模板中将变量值的第一个字母大写
【发布时间】:2011-01-18 03:50:02
【问题描述】:

我有一个带有变量的代码模板,我想仅在某些情况下将这个变量的值大写(只是第一个字母)。有没有办法做到这一点?

模板代码如下 - 我想在我的函数名中将 Property Name 大写...

private $$${PropertyName};
${cursor}    
public function get${PropertyName}() 
{
  return $$this->${PropertyName};
}

public function set${PropertyName}($$value) 
{
  $$this->${PropertyName} = $$value;
}

请注意:这是一个在 IDE(不是 PHP)中与代码模板一起使用的模板。详情见:http://www.ibm.com/developerworks/opensource/tutorials/os-eclipse-code-templates/index.html

【问题讨论】:

    标签: eclipse


    【解决方案1】:

    我也想要这个,并尝试构建一个自定义 TemplateVariableResolver 来做到这一点。 (我已经有了一个自定义解析器,可以生成新的 UUID,例如 http://dev.eclipse.org/blogs/jdtui/2007/12/04/text-templates-2/。)

    我做了一个绑定到capitalize的自定义解析器:

    public class CapitalizingVariableResolver extends TemplateVariableResolver {
        @Override
        public void resolve(TemplateVariable variable, TemplateContext context) {
            @SuppressWarnings("unchecked")
            final List<String> params = variable.getVariableType().getParams();
    
            if (params.isEmpty())
                return;
    
            final String currentValue = context.getVariable(params.get(0));
    
            if (currentValue == null || currentValue.length() == 0)
                return;
    
            variable.setValue(currentValue.substring(0, 1).toUpperCase() + currentValue.substring(1));
        }
    }
    

    (plugin.xml:)

    <extension point="org.eclipse.ui.editors.templates">
      <resolver
            class="com.foo.CapitalizingVariableResolver"
            contextTypeId="java"
            description="Resolves to the value of the variable named by the first argument, but with its first letter capitalized."
            name="capitalized"
            type="capitalize">
      </resolver>
    </extension>
    

    我会这样使用:(我在 Java 中工作;我发现您似乎不是)

    public PropertyAccessor<${propertyType}> ${property:field}() {
        return ${property};
    }
    
    public ${propertyType} get${capitalizedProperty:capitalize(property)}() {
        return ${property}.get();
    }
    
    public void set${capitalizedProperty}(${propertyType} ${property}) {
        this.${property}.set(${property});
    }
    

    从 Eclipse 3.5 开始,我遇到的问题是,一旦我为 property 变量指定了值,我的自定义解析器就没有机会重新解析。 Java 开发工具 (Eclipse JDT) 似乎通过 JavaContext 中称​​为 MultiVariableGuess 的机制重新解析了这个依赖模板变量(请参阅 addDependency())。对我们来说不幸的是,该机制似乎没有暴露出来,所以我/我们不能用它来做同样的事情(没有大量的复制和粘贴或其他多余的工作)。

    在这一点上,我再次放弃一段时间,并将继续将前导小写和前导大写名称分别输入到两个独立的模板变量中。

    【讨论】:

    • 这是一个很好的答案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2017-06-20
    • 2016-01-25
    • 2019-08-19
    • 1970-01-01
    相关资源
    最近更新 更多