Skip to content

Instantly share code, notes, and snippets.

@kjlubick
Created June 10, 2014 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjlubick/c7cb9c28dfb95139de6f to your computer and use it in GitHub Desktop.
Save kjlubick/c7cb9c28dfb95139de6f to your computer and use it in GitHub Desktop.
How to access the source code from FindBugs
private String[] getSourceLines(Method obj) {
BufferedReader sourceReader = null;
String[] sourceLines;
try {
srcLineAnnotation = SourceLineAnnotation.forEntireMethod(getClassContext().getJavaClass(), obj);
if (srcLineAnnotation != null)
{
SourceFinder sourceFinder = AnalysisContext.currentAnalysisContext().getSourceFinder();
SourceFile sourceFile = sourceFinder.findSourceFile(srcLineAnnotation.getPackageName(), srcLineAnnotation.getSourceFile());
sourceReader = new BufferedReader(new InputStreamReader(sourceFile.getInputStream(), "UTF-8"));
List<String> lines = new ArrayList<String>(100);
String line;
while ((line = sourceReader.readLine()) != null)
lines.add(line);
sourceLines = lines.toArray(new String[lines.size()]);
}
} catch (IOException ioe) {
//noop
}
finally {
try {
if (sourceReader != null)
sourceReader.close();
} catch (IOException ioe2) {
//noop
}
}
return sourceLines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment