Friday Apr 18, 2008

Nested JavaScript functions and Non-static Inner Classes in Java


I am a Java programmer and understand the Java language concepts such as inner classes and scoping rules well. I have been learning JavaScript and trying to understand the scoping rules in JavaScript. Here are some of my observations about the similarities and differences between some aspects of nested JavaScript functions and Non-static inner classes.

var global = 0;
function outerFunction() {
var outerLocal = 1;
function innerFunction() {
var innerLocal = 2;
// Can access outerLocal here
// Can access global here

return innerFunction;




outerFunction.staticVar = 10; 
// elsewhere
function callingFunction() {
// Get a reference to innerFunction()
var refToOuterDotInner = outerFunction();


public class Outer() {
public static int staticField = 10;
private int outerLocal = 1;
public class Inner() {
private int innerLocal = 2;

private void innerMethod() {

int methodLocal = 4;
// Can access innerLocal here
// Can access outerLocal here

public Inner getInner() {
return new Inner();

// elsewhere
public void callingMethod() {
Outer outer = new Outer();
Inner innerInstance = outer.getInner();
// Invoke method of inner class

innerFunction() is analogous to --------->

The scope of innerFunction() maps to two concepts in Java world - the scopes of innerMethod() and the instance of Inner class.

The execution call stack of innerFunction() maps to the innerMethod() though.

 innerMethod() and instance of Inner class

I think this is the source of confusion for Java programmer. At least it was to me.

Three scopes when the innerFunction is executing:

  • Global
  • scope of outerFunction
  • scope of innerFunction - maps to last two scopes on Java side

Three scopes when innerMethod() is executing.

  • No equivalent in Java
  • Outer instance scope
  • Inner instance scope
  • innerMethod() local scope

outerLocal in outerFunction is analogous to --------->

outerLocal is private to outerLocal but can be accessed from innerFunction() .

outerLocal field of an instance of Outer class.

outerLocal is private to the instance of Outer class but can be accessed from innertMethod() .

In terms of scope level innerLocal is analogous to --------->methodLocal and innerLocal
no analogue
the Outer class instance can be accessed using Outer.this

call stack involves:


call stack:


outerFunciton.staticVar is analogous to --------->

Note the absence of  () after outerFunction.

static access to Outer.staticField


The scoping and access level rules of the inner functions allow for closures (a powerful concept) in JavaScript.

Do you have any insights to share?

Tuesday Dec 25, 2007

Reorder module on NetBeans Plugin POrtal

I have uploded the Reorder module to the NetBeans Plugin Portal.

The assymetry in the way ,  (comma)  is used to separate the items in parameter and arguments lists always causes problem when one wants to reorder that list in Java editor.  Is that why Java allows trailing commas in array initializer? ;) may be. This module supports single click swapping of a parameter, argument or array initializer expressions with pervious or next item in the list. Each item of the sequence can be a simple literal, an identifier or a more complex function call expression. The comma delimiter is correctly handled.

For example with caret at | in:

void method(int iii, String |sss, boolean bbb){}
pressing CTRL+ALT+. (i.e. period) or invoking Source:Swap Next action yields:
void method(int iii, boolean bbb, String |sss){}
or pressing CTRL+ALT+, (i.e. comma)
or invoking Source:Swap Previous action with the original source yields:
void method(String |sss, int iii, boolean bbb){}


DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

Tuesday Dec 04, 2007

ScreenMetrics tool

Here is a simple (whacky) desktop utility to measure distances on your screen:

Screen Metric

You can drag the thin vertical and horizontal lines, horizontally and vertically respectively to measure distance between them which is displayed in the toolbar like gadgets. The format is max marker location - min marker location = distance. The location and distance values are continuously updated as you drag the lines. You can use the spinner controls to increment or decrement the location of minimum or maximum markers. You can directly type the location value also.You can move the toolbar gadgets around by dragging on the left or right edge of the toolbars.

This is not a NetBeans Module. It is a Desktop utility. It was built using NetBeans of course :)

To run:

Download ScreenMetrics.jar and type:

> java -jar ScreenMetrics.jar

Hacking: contains the NetBeans project.


  • Show the distance value in other units e.g. inches, cms, picas?, em?
  • Show the area
  • Handle multiple monitor scenarios correctly
  • ability to show and hide
  • Precise control on moving using spinners - Done

DISCLAIMER: This module is tool. So no guarantees. Use the module at your own risk.

Monday Dec 03, 2007

Add Property module functionality in trunk

With this check in the Add Property module's functionality is available in trunk. Thanks to Jan Lahoda. The functionality is available through the Add Property popup menu in the Generate Code (Alt+Insert) popup menu in Java Editor.

Thursday Nov 29, 2007

Which Tree module on NetBeans Plugin Portal

I have uploaded the WhichTree module to the NetBeans Plugin Portal.

This module shows information about the Javac Tree Path at the caret position in current Java editor in a read-only text field in the status bar. The information is updated as the caret moves. The text field can be hidden and shown using the button on it's left. The tool tip shows the full text so that it can be seen when it is wider than 40 columns.

Which Tree


Double clicking on the text field shows a dialog which shows the Tree Path in a tree. The source for the selected Tree is shown in a text area. This is a good tool to understand how the Javac sees the Java source. The IDs shown in the tree are the TreeKind enumeration values.


Tree Path details


This is along the lines of WhichElement module I blogged about a few months ago. 


Sources (on branch release60)

DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

Friday Nov 23, 2007

Tip: api to show Java type chooser dialog in NetBeans 6.0

While implementing the Add Property module, Jan Lahoda pointed out an api available in NetBeans 6.0 Java support which can show a Java Type chooser dialog. Here is the snippet of code to show the dialog:

        FileObject fileObject = ...; // Some java file's file object in a NetBeans Project.

ElementHandle<TypeElement> type = TypeElementFinder.find(ClasspathInfo.create(fileObject), null);

if (type != null) {
// use the type somehow

which shows the dialog:

Find Type dialog

You can use this api in your module any time you want to select a Java type. You will have to add the following dependencies to your module:

  • Java Source
  • Java Source UI
  • Java Support APIs
  • Javac API Wrapper

The TypeElementFinder api is implemented in Java Source UI module. You can further customize the dialog by passing the second argument to the find() method.

For some reason this does not appear in the NetBeans 6.0 API docs - probably because this is not an official API yet.

Wednesday Nov 21, 2007

JPDA (Java) Debugger Threads View Enhancements module on NetBeans Plugin Portal

I have uploaded the JPDA (Java) Debugger Threads View Enhancements module module to the NetBeans Plugin Portal.

Enhanced Threads View

This module unifies Threads and Call stack view (somewhat like Eclipse Java Debugger Threads View). The call stack frames are shown as the children of suspended thread in the Threads view. It supports same actions on as Call Stack view and more. For example, it shows actions to jump to types of local variable of a Call stackframe as well as the Show Classes action. It also shows full method signature of the Call stack frame. It additionally shows the actual class of the 'this' variable if it differs from the class that declares the method of the call stack frames.

The Show Classes action shows all the classes loaded in the JVM along with the loading and initiating ClassLoaders. This is useful for debugging class loading in multi-ClassLoder appications such as NetBeans itself.

Classes view


DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

Thursday Nov 15, 2007

Highlight Boxing Unboxing Varargs module on NetBeans Plugin Portal

I have uploaded the Highlight Boxing Unboxing Varargs module to the NetBeans Plugin Portal. It enables highlighting of occurences of boxing, unboxing and varargs in the Java editor. Obviously this only works for files belonging to projects with source level set to 1.5+.

UPDATE: The download link on the Plugin Portal has now been fixed.

The Java compiler silently applies the boxing and unboxing to the primitive types and the corresponding reference types as needed. This module reveals where that may be happening in your code. This module may help you diagnose mysterious NPEs when a reference type null value is attempted to be unboxed at runtime (well the example in the screen shot is not the best ;) ). To turn the highlighting on or off use the toggle buttons on the toolbar. Here is a screen shot:

NetBeans Java Editor showing highlighted boxing, unboxing and varargs occurences

Jan Lahoda contributed to this module.


DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

Sunday Nov 04, 2007

Add Property module on NetBeans Plugin Portal

I have uploaded the Add Property module to the NetBeans Plugin Portal. It installs the action Source:Add Property. Invoking the action shows the following dialog.

Add Property Dialog


You can configure the property settings. The preview window shows what code will be inserted in Java editor. Select OK to insert the code at current caret position.


You can customize the template by editing it using the Tools:Templates action.

Template Manager Dialog

The template uses the freemarker template engine.



  • validation of name and type
  • validation of duplicate property name
  • browse to select type
  • nicer positioning of the field, getters and setters
  • insertion of required import statements instead of using FQNs


DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.

Friday Oct 19, 2007

Java Decl Gen module

I have uploaded the Java Decl Gen module on the Plugin Portal.

This module supports several forms of parameter, variable, array parameter and array variable declarations.

These actions were formerly part of the contrib/CamelCase module. The CameCase movement and selections are now part of NetBeans 6.0 Java editor.

Assuming you have typed:


in the Java editor you can invoke the following actions:

ActionKey binding
Declare Parameter e.g. Foo foo |Alt+U SPACE
Declare Parameter with comma e.g. Foo foo, |Alt+U ,
Declare Variable e.g. Foo foo;|Alt+U ;
Declare Variable with initializer e.g. Foo foo = new Foo()|;Alt+U =
Declare Variable with casted initializer e.g. Foo foo = (Foo)|;Alt+U (
Declare Array Parameter e.g. Foo[] foos|Ctrl+Alt+U SPACE
Declare Array Parameter with comma e.g. Foo[] foos, |Ctrl+Alt+U ,
Declare Array Variable e.g. Foo[] foos;|Ctrl+Alt+U ;
Declare Array Variable with initializer e.g. Foo[] foos = new Foo[]{};|Ctrl+Alt+U =
Declare Array Variable with casted initializer e.g. Foo[] foos = (Foo[]) ;|Ctrl+Alt+U (

The highlighted regions behave like editor code templates. Use ENTER to escape the code template parameter editing mode - then the cursor will be positioned at |.


  • Use the same algorithm as the one used by Java Editor to generate proposed parameter or variable names.


DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.


Friday May 11, 2007

How is it implemented? Java Editor Hint: Change variable type fix

In the previous entry I talked about the Change Variable Type fix. In this entry I will talk about how it is implemented.

Registration of the factory

Like many other features in NetBeans the hints/fixes/suggestions are implemented using a factory mechanism. The factory is registered in the module's layer file like this:

  <folder name="org-netbeans-modules-java-hints">
    <folder name="rules">\\
      <folder name="errors">
        <file name="org-netbeans-modules-javahints-ChangeTypeCreator.instance"/>

The factory is registered under the org-netbeans-modules-java-hints/rules/errors folder because it creates a fix for certain compilation errors such as type mismatch of the left and right side of a vatriable declaration statement.

Implementation of the factory

As the user edits the source code, the Java editor incrementally runs the javac in the background. As the javac emits compilation errors the editor shows the red squiggly lines. Aside from that it also invokes the factories registered to handle the particular compilation errors. In this case org.netbeans.modules.javahints.ChangeTypeCreator is one such factory. The ChangeTypeCreator implements the interface This intreface essentially has two important method:

    /\*\* Get the diagnostic codes this rule should run on
    public Set<String> getCodes();
    /\*\* Return possible fixes for a given diagnostic report.
    public List<Fix> run(CompilationInfo compilationInfo,
                         String diagnosticKey,
                         int offset,
                         TreePath treePath,
                         Data<T> data);

The getCodes() method essentially indicates the set of compilatioin error codes that are handled by the factory. The ChangeTypeCreator handles:


These codes are part of standard error codes emitted by the javac.

In the run(...) method of ChangeTypeCreator,enough information about the context in the editor is passed in. The ChangeTypeCreator uses the APIs to determine the types of expressions on the left and right side of a variable assignmenets and returns an instance of org.netbeans.modules.javahints.ChangeTypeHint. This instance is used to populate the list of fixes that appear as actions in the light bulb pop up menu in the left margin of the editor.

Implementation of the Change variable type fix

The ChangeTypeHint which implements org.netbeans.spi.editor.hints.Fix . It provides the text of menu item which is returned from:

    public String getText()

The actual fix is implemented in the method:

 public ChangeInfo implement()

using the Java Source APIs.

Friday May 04, 2007

Java Editor Hint: Change variable type fix

In NetBeans 6.0 Java editor supports writing custom, so called, fixes, hints and suggestions. These appear as a light bulb icon in the left margin of the Java editor. For example, in the code below:

100        List list = ...;
101        :
110        String s = list.get(0);

the type of the variable s does not match the type of the expression list.get(0). In such cases a light bulb icon appears in the left margin of the Java editor on the line 110 of the code. Clicking or invoking the fix action reveals a menu item saying Cast ...get(...) to String. Selecting the menu item changes the code on line 110 to:

110        String s = (String) list.get(0);

This is all well and good. However what if you wanted to adjust the type of the variable s to Object. It is very easy to write such a fix and that is what I have implemented.

With this fix, I always write my variable like this:

110        int i = .....; // some expression that return a type I don't know - assume it is RefactoringPluginFactory

Select the hint to change the type of i to the correct type.

110        RefactoringPluginFactory i = ....; 

(I know, I know some may say why I am doing this...because I am an extremely poor typist :( )
Then I quickly delete i and use the smart variable name proposal code completion to get:

110        RefactoringPluginFactory refactoringPluginFactory = ....;

I have added the fix to the Experimental Java Hints (contrib/editorhints/java) module. You can get the module from Development Update center.


DISCLAIMER: This module is experimental. So no guarantees. Use the module at your own risk.




« June 2016