Monkey patching a Java class?

A. Sundararajan sundararajan.athijegannathan at oracle.com
Mon Jul 21 11:07:10 UTC 2014


No, you can't add new methods to extended class (no facility to declare 
types and so on) - only overrides of super class methods.

-Sundar

On Sunday 20 July 2014 10:28 PM, Marc Downie wrote:
> Does adding new methods to Java.extend based subclasses actually work?
> Currently I have (staying close to the example code):
>
> var ArrayList = Java.type("java.util.ArrayList")
> var ArrayListExtender = Java.extend(ArrayList)
> var printSizeInvokedArrayList = new ArrayListExtender() {
>      size: function() { print("size invoked!"); },
>    banana: function() { print("Banana"); } // this doesn't override anything
> in ArrayList
> }
>
> printSizeInvokedArrayList.size() // WORKS
> printSizeInvokedArrayList.banana() // TYPE ERROR ([] has no such function
> "banana")
>
> // and even:
>
> printSizeInvokedArrayList.peach = function(){print("Peach");} // no error,
> but....
> printSizeInvokedArrayList.peach() // TYPE ERROR ([] has no such function
> "peach")
>
> (1.9.0-ea-b23 and 1.8.0_20-ea-b23)
>
> Marc.
>
>
>
> On Thu, May 1, 2014 at 11:23 PM, A. Sundararajan <
> sundararajan.athijegannathan at oracle.com> wrote:
>
>> 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
>> "java.io.File" by
>>
>>      var oldFile = java.io.File;
>>      java.io.File = Java.extend(oldFile, ...)
>>
>> But, I'd not recommend it - besides user can still get original
>> java.io.File via Java.type (unless you do similar hack on Java.type as
>> well!!)
>>
>> Cleaner approach is to expose a script API wrapping java.io.File.
>>
>> -Sundar
>>
>>
>> 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 java.io.File class, say
>>> "readAsString()".
>>>
>>> Then, in javascript I want to call file.readAsString()  where file is an
>>> instance of java.io.File. 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,
>>> HRJ
>>>
>>



More information about the nashorn-dev mailing list