Java 如何在Eclipse中查找过程开头的行号
我有一段代码可以在Windows下的Eclipse中正确地找到I方法的行号:Java 如何在Eclipse中查找过程开头的行号,java,eclipse,Java,Eclipse,我有一段代码可以在Windows下的Eclipse中正确地找到I方法的行号: IMethod method= ...; String source= type.getCompilationUnit().getSource(); int lineNumber= 1; for (int i= 0; i < method.getSourceRange().getOffset(); i++) if (source.charAt(i) == Character.LINE_SEPARATOR)
IMethod method= ...;
String source= type.getCompilationUnit().getSource();
int lineNumber= 1;
for (int i= 0; i < method.getSourceRange().getOffset(); i++)
if (source.charAt(i) == Character.LINE_SEPARATOR)
lineNumber++;
IMethod=。。。;
字符串源=类型.GetCompliationUnit().getSource();
int lineNumber=1;
对于(int i=0;i
但是,这在Mac上不起作用,假设行分隔符字符不同,即使它所操作的源代码相同
Kent Beck您可以使用
BufferedReader
实例包装字符串,该实例支持readLine()
方法。这个方法可能正确地解析了任何类型的分隔符。我不能回答(1),但我会尝试(2)
奇怪的是,我认为你的代码只是巧合。表示Unicode类别;它不应该是该平台的换行符,但它恰好有价值,而这(正如您可能知道的)是。如果我没记错的话,自从OSX以来,Mac一直使用'\n'
作为换行符,所以这就是它不起作用的原因
我过去获得行分隔符字符的方式是。这将返回一个字符串
,因此它可能不合适。由于它似乎在Windows上与'\r'
一起工作,我想对'\n'
进行简单的检查也就足够了。或者,您可以使用一个围绕a的BufferedReader
,正如Wouter Lievens建议的那样。您可以使用中使用的由a构建的(不计算行数,但它仍然给出了想法)
希望IScanner的内部eclipse实现能够在任何平台上正常工作
IBuffer buffer = imethod.getOpenable().getBuffer();
ISourceRange sourceRange = imethod.getSourceRange();
ISourceRange nameRange = imethod.getNameRange();
IScanner scanner = null; // delay initialization
if (sourceRange != null && nameRange != null) {
if (scanner == null) {
scanner= ToolFactory.createScanner(false, false, true, false);
scanner.setSource(buffer.getCharacters());
}
scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset());
} else {
return 0 // no lines;
}
// use scanner to count lines
我最终使用了regex,因为它更简单。这使得代码O(n^2)在我需要在文件中采用的方法的数量上有所增加,但我希望这应该是一个较小的数量,所以现在可以接受
private int getMethodLineNumber(final IType type, IMethod method) throws JavaModelException {
String source= type.getCompilationUnit().getSource();
String sourceUpToMethod= source.substring(0, method.getSourceRange().getOffset());
Pattern lineEnd= Pattern.compile("$", Pattern.MULTILINE | Pattern.DOTALL);
return lineEnd.split(sourceUpToMethod).length;
}
谢谢大家的帮助
问候,
Kent将lineEnd设为常量会更快,这样就不必每次调用该方法时都编译它。当然,对于这样一个小模式,这不太可能有多大区别。