在 eclipse 插件中使用行号突出显示来自 jdt java 文本编辑器的文本

Highlight text from jdt java text editor using line numbers in eclipse plugin

我正在尝试编写一个 eclipse 插件,在用户保存文本 (ResourceChangeListener) 后突出显示 java 编辑器中的一些文本。我正在实施 ILightweightLabelDecorator 并扩展 BaseLabelProvider,方法

public void decorate(Object arg0, IDecoration arg1)

正在调用,但我收到类型为 org.eclipse.jdt.internal.core 的对象。* 例如 org.eclipse.jdt.internal.core.PackageDeclaration。 我需要该对象的行号,以便突出显示该文本。 ASTNode 对象有一个 属性 来获取位置(行号),但我没有得到那个。如何从 org.eclipse.jdt.internal.core.* 获取 ASTNode 对象?

提前致谢。

PackageDeclaration 是 JDT Java Model 的一部分,它是许多 Java 代码使用的 AST 的轻量级版本。因此它与 ASTNode.

无关

许多 Java 模型对象(包括 PackageDeclaration)实现了 ISourceReference,它告诉您有关源代码的信息。这包括 getSourcegetSourceRange 方法。

我们可以使用下面的方法获取行号,

    private int getLineNumberInSource(SourceRefElement member) throws 
JavaModelException { 
    if (member == null || !member.exists()) { 
        return -1; 
    } 
    ICompilationUnit compilationUnit = member.getCompilationUnit(); 
    if (compilationUnit == null) { 
        return -1; 
    } 
    String fullSource = compilationUnit.getBuffer().getContents(); 
    if (fullSource == null) { 
        return -1; 
    } 
    ISourceRange nameRange = member.getNameRange(); 
    if (nameRange == null) { 
        return -1; 
    } 
    String string2 = fullSource.substring(0, nameRange.getOffset()); 
    return 
            string2.split(compilationUnit.findRecommendedLineSeparator()).length; 
}