Here's a way to create a custom Hover on the Default Java Editor.
Here's a custom implementation of @PKeidel's LangHover class from that question for your specific use case, combined with a custom script to detect java elements. Note that you should change ANNOTATION_NAME
's value to the value of your custom Annotation, and the return value of getHoverInfo
to whatever you want the custom hover to contain.
public class LangHover implements IJavaEditorTextHover
{
public static final String ANNOTATION_NAME = "YourCustomAnnotation";
@SuppressWarnings("restriction")
public static ICodeAssist getCodeAssist(IEditorPart fEditor)
{
if (fEditor != null) {
IEditorInput input= fEditor.getEditorInput();
if (input instanceof IClassFileEditorInput) {
IClassFileEditorInput cfeInput= (IClassFileEditorInput) input;
return cfeInput.getClassFile();
}
WorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(input, false);
}
return null;
}
public static IEditorPart getActiveEditor()
{
IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page= window.getActivePage();
if (page != null) {
return page.getActiveEditor();
}
}
return null;
}
// When this returns true, the custom hover should be shown.
public static boolean elementIsCustomAnnotation(ITextViewer textViewer, IRegion hoverRegion)
{
IEditorPart activeEditor = getActiveEditor();
ICodeAssist resolve = getCodeAssist(activeEditor);
IJavaElement[] detectedJavaElements = null;
if (resolve != null)
{
try
{
detectedJavaElements = resolve.codeSelect(hoverRegion.getOffset(), hoverRegion.getLength());
}
catch (JavaModelException x)
{
System.out.println("JavaModelException occured");
}
}
for (IJavaElement javaElement : detectedJavaElements)
{
// If I found an element of type IJavaElement.ANNOTATION
// and its name equals ANNOTATION_NAME, return true
if (javaElement.getElementType() == IJavaElement.ANNOTATION && javaElement.getElementName().equals(ANNOTATION_NAME))
{
return true;
}
}
return false;
}
@Override
public String getHoverInfo(ITextViewer textviewer, IRegion region)
{
if(elementIsCustomAnnotation(textviewer, region))
{
return "Your own hover text goes here"";
}
return null; // Shows the default Hover (Java Docs)
}
}
Basically, what is happening here is that elementIsCustomAnnotation
is checking the java element(s) the user is hovering over, puts them in the detectedJavaElements
array, and then checks that array to find an Annotation with name equal to ANNOTATION_NAME
.