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 BinaryElementOpen and 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 {...
    

    position attribute 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 open method. 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

One Response to How to write your source provider for class in Netbeans

  1. Pingback: JavaPins

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: