How to write your source provider for class in Netbeans
I’ve been recently writing plugin for Netbeans IDE that should return source from some custom place when you do Ctrl+click or Go-to type for class that source could not be found.
It took me some time to find this out, but stuff is pretty easy in 6.8 and above.
- First you need to implement
BinaryElementOpenand declare service provider for
BinaryElementOpen.class.
It’s quite simple if you use annotations, no ugly layer.xml needed:):
@org.openide.util.lookup.ServiceProvider(service = org.netbeans.modules.java.BinaryElementOpen.class, position = 20) public class GrokElementOpen implements BinaryElementOpen {...
positionattribute is used to choose which provider should be executed first (yours go first if you give it 0 and last if you give it some large number).
- Next you implement
openmethod. And here is some ugly hack I have used to quickly get class that has to be found:
@Override public boolean open(ClasspathInfo cpInfo, ElementHandle<? extends Element> toOpen) { //XXX: UGLY HACK, find some api that will get class name for field, etc (getQualifiedName fails for something else then classes) Field sigFields = toOpen.getClass().getDeclaredField("signatures"); sigFields.setAccessible(true); String[] signatures = (String[]) sigFields.get(toOpen); if (signatures != null && signatures.length > 0) { String className = signatures[0]; //XXX: End of UGLY HACK ... }
Simply couldn’t find something nice to do this, and i needed class name.
- All you have to do next is open file on line that contains stuff user clicked:
File savedFile= new File(savedIn, name); FileObject dataFile = FileUtil.createData(savedFile); ElementOpen.open(dataFile, toOpen);
- And return true if you succeeded or false otherwise (so Netbeans infrastructure keeps searching).
That’s all. Compile, create NBM and you’re done. Here is your custom source provider.
Advertisements
Pingback: JavaPins