简体   繁体   中英

How to write new methods in predefined java classes

I want a swap method for array objects that could swap two numbers in the array

int[] a = new int[5];
a.swap(i, j);

which could swap elements at i and j

Also I don't want another method that takes array as an argument and does a swap like thus

swap(a,i,j) where a is array object; i and j are indexes

This is not possible in java. This concept (where code is grafted onto a type; the central notion being that the code being grafted on lives separate from the code that defines the original type) is called 'extension methods' or 'monkey patching'.

'Extension methods' tends to refer to the notion that at some level in your source code, such as per file, per directory, per package, or per project, you explicitly document a repository of extensions, and these then count for the entire file/directory/package/project). It's a compile-time concept.

'Monkey patching' refers to the notion that at runtime you dynamically extend a class or even a single object; this fits more in languages where 'everything is a dictionary' such as javascript or python.

Java is the kind of language where you'd have extension methods.

As of early november 2019 (SOURCE: I asked Brian Goetz at Devoxx 2019 about it), this is intentional and the current shepherds of the language have no intention of changing it; they believe it is better to be explicit about where source lives.

NB: You can use Project Lombok's@ExtensionMethod feature if you just must have them (of which I am a developer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM