Monkey patching a Java class?

A. Sundararajan sundararajan.athijegannathan at
Fri May 2 04:23:32 UTC 2014

No, you can't add/remove a method (or public field) of a Java class to 
use within the script. You could subclass and expose that subclass as 
"" by

     var oldFile =; = Java.extend(oldFile, ...)

But, I'd not recommend it - besides user can still get original via Java.type (unless you do similar hack on Java.type as 

Cleaner approach is to expose a script API wrapping


On Thursday 17 April 2014 12:03 AM, HRJet wrote:
> Is it possible to monkey patch a Java class for use within Javascript?
> For example, I want to add a convenience method to class, say
> "readAsString()".
> Then, in javascript I want to call file.readAsString()  where file is an
> instance of Note that the file instance may be created by
> some third-party code, over which I have no control.
> In Java land, this seems to be usually done with CGLib or AspectJ, etc.
> I was wondering if nashorn had some trick up its sleeve for doing this in
> script land, since this sort of thing is common in Javascript.
> thanks,

More information about the nashorn-dev mailing list