Does Java support Swift-like class extensions? - java

In Swift, you can create extension of existing class to add additional functions to the existing class whenever it is needed. This also helps to avoid creating a subclass of the existing class.
I was just wondering if there is a similar function exist in Java? or is it the only way to add additional methods to a existing Java class is to create a subclass of the existing class?

No, vanilla Java does not feature extension methods. However, Lombok adds many useful features - including extension methods syntax - thanks to its annotations and bytecode generation.
You can use its #ExtensionMethod annotations to "convert" existing static methods to extension methods. The first parameter of the static methods basically becomes this. For example, this is a valid Lombok-enhanced Java code:
import lombok.experimental.ExtensionMethod;
#ExtensionMethod({java.util.Arrays.class, Extensions.class})
public class ExtensionMethodExample {
public String test() {
int[] intArray = {5, 3, 8, 2};
intArray.sort();
String iAmNull = null;
return iAmNull.or("hELlO, WORlD!".toTitleCase());
}
}
class Extensions {
public static <T> T or(T obj, T ifNull) {
return obj != null ? obj : ifNull;
}
public static String toTitleCase(String in) {
if (in.isEmpty()) return in;
return "" + Character.toTitleCase(in.charAt(0)) +
in.substring(1).toLowerCase();
}
}
Note that Lombok extension methods can be "invoked" on null objects - as long as the static method is null-safe, NullPointerException will not be thrown, as this is basically translated to static method call. Yes - it comes down to syntax sugar, but I guess this is still more readable than the usual static methods calls.
Aside from that, you can use some other JVM language with Java interoperability, if that's OK in your project. For example, Kotlin comes with extension methods functionality, as well as some useful extensions already defined in the standard library. Here's a Kotlin and Lombok comparison.

The Decorator Pattern is perhaps the closest match. It uses interface to maintain the type compatibility and composition to enhance the existing class' function. It's not the same principle as the one you're describing but might serve the same purpose.

It can be done in other languages for JVM, like Scala, Groovy or Closure.
For example in Groovy:
List.metaClass.printSize = {
println delegate.size()
}
[1,2,3].printSize() //prints 3
In Scala you can use implicit class:
implicit class PrefixedString(val s: String) {
def prefix = "prefix_" + s
}
"foo".prefix // returns "prefix_foo"
Please have a look at this article.
An important remark is that Groovy/Scala source code is intended to be compiled to Java bytecode so that the resulting classes can be used in Java code.

Related

Is there any way to check whether a given class type belongs to Java object or custom object

I was searching for any ways to check whether the type of the given attribute of a class is of custom object type (for eg., Person) or Java object (for eg., String, Long, primitive types as well) type. If instanceof is used, it will be hectic checking all of the Java types. Can anyone suggest a way to check, if anything as such exists.
Java is very much "built on itself". Much of the SDK could be considered both "custom" or "built-in" depending on which way you are looking at it.
For instance, Exception is built in to Java but also written in Java. You could write similar code yourself, however based on what you've said I am guessing you would consider it a "Java object".
Similarly, ArrayList is also written in Java, but because it's a utility class, I'm guessing you would consider it "custom", though I'm not sure, since it is still included in the SDK.
Without knowing exactly what you are looking for, the closest grouping that I can guess based on what you've said (String, Long, etc.) is the java.lang package. In the words of the SDK documentation itself, the java.lang package:
Provides classes that are fundamental to the design of the Java programming language.
You can check if the package name of the class for the object is in java.lang:
static class A {
}
public static void main (String[] args) {
String test1 = "";
A test2 = new A();
int test3 = 3;
System.out.println(isJavaLang(test1));
System.out.println(isJavaLang(test2));
System.out.println(isJavaLang(test3));
}
public static boolean isJavaLang(Object check) {
return check.getClass().getName().startsWith("java.lang");
}
Working example
There's no fail-safe method to do this. As others said, Java builds a lot on regular classes.
I guess that, appart from primitives, it all boils down to your own definition of "JDK's classes" vs "my classes" vs "3rd party classes".
#splungebob's solution works for your own, single tree-branch classes.
I would think that classes from the following packages can be safely, if minimallistically, regarded as JDK's:
java.lang.*
java.*
javax.*
com.sun.*
com.oracle.*
You might also add some common 3rd parties like org.apache.*
Try maybe using implementation vendor title of package that object is coming from. It seems that standard Java packages have this value set to "Oracle Corporation". "Java Runtime Environment".
public static boolean isJavaLang(Object check) {
if (check == null)// lets say that null comes from JRE
return true;
return isJavaLang(check.getClass());
}
public static boolean isJavaLang(Class<?> check) {
Package p = check.getClass().getPackage();
if (p == null) // default package is package for users classes
return false;
String title = p.getImplementationTitle();
if (title == null)// no title -> class not from Oracle
return false;
// System.out.println(p.getImplementationVendor());
// System.out.println(p.getImplementationTitle());
return title.equals("Java Runtime Environment");
}
I'm not entirely sure I got your question right...
The java.lang.Class class features some tools you can use.
The isPrimitive() function
Determines if the specified Class object represents a primitive type.
There are nine predefined Class objects to represent the eight primitive types and void. These are created by the Java Virtual Machine, and have the same names as the primitive types that they represent, namely boolean, byte, char, short, int, long, float, and double.
These objects may only be accessed via the following public static final variables, and are the only Class objects for which this method returns true.
As for the other classes, there is no such thing as a "Java object" - every object is a Java object... But you could for example check if the name of the class in question begins with java.lang. prefix, but the java.lang package contains a lot different things too, not only the basic datatypes you'd like to find.
I think you want something like:
public static boolean isJavaObject(Object obj)
{
return (! obj.getClass().getName().startsWith("my.package"));
}
where "my.package" is the head of your package heirarchy.
Suppose that your own classes aren't located within packages whose names start with java*:
public static <T> boolean isJDKClass(T t) {
return t.getClass().getPackage().getName().startsWith("java");
}

Can you declare parameter-less methods in Java for use in Scala?

In Scala we can have parameterless methods, which can be very useful for DSL purposes; they are also used for auto-defining getters for class fields.
I am developing a Java library that I would like to integrate as seamlessly with Scala as possible. I was wondering if there is a way to annotate a Java method with an empty parameter list so that Scala recognize it as parameterless.
For instance
class Foo {
#ParameterLess
public String[] bar() { return someArray; }
}
so that in Scala I can do:
val f = new Foo
f bar (0)
without having the compiler to complain about bar() having an empty argument list?
Alternatively, is there a way to define Scala-style getters and setter from Java?
Note: of course I know that in this particular example I can workaround the problem by defining
public String bar(int i) { return someArray[i]; }
This probably answers my question:
Scala getters and setters in Java class
The answer is that you can't, unless you resort to some trickery involving traits. Well, I guess that some kind of annotation à la #scala.reflect.BeanProperty would be a useful improvement.

Would this addition to Java be hard to implement?

I often wanted to be able to decorate java-classes properly, that is add behaviour to them. I know mixins from ruby, and i know that they can get terribly confusing.
I came up with the theoretical idea of having a language-construct like this:
package org.test.decorator;
public decorator ListPatch<E> extends List<E> {
public E last() {
return this.get(this.size() - 1);
}
}
this would give access to public members of List and the Decorator itself.
Then in a class i could use:
package org.test.decorator;
decoration org.test.decorator.ListPatch;
public MyClass {
public void foo() {
List<String> list = Lists.newArrayList();
list.add("test");
System.out.println(list.last());
}
}
I don't have that much knowledge about compilers, so I wondered if something like that was possible. Also if it actually would be an improvement.
Sure, it's possible.
The fact that Scala compiles to bytecode (and has a fairly straight forward mapping from Scala classes to bytecode classes) and supports mixins proves this.
Here's how your sample code looks in Scala syntax:
class ListTest {
// ...
}
trait ListPatch {
def last {
// ...
}
}
object Main {
def main(args: Array[String]) {
val list = new ListTest() with ListPatch;
list.add("test")
println(list.last)
}
}
Scala compiles this by adding an axillary class Main$$anon$1 which composes ListTest and ListPatch.
The motto for the Java developers have always been (and will probably always be) "If in doubt, leave it out." though.
Related questions:
Implement Mixin In Java?
Not really an Answer to your question but you can solve this problem with inversion of control/dependency injection (just like you did in your code)
basically:
don't use "new ArrayList()" but instead some factory like "injector.new(ArrayList.class)". This injector can now override the wanted class and return an Object which extends ArrayList decorated with your methods.
Your idea sounds much like Extension methods in C#.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
In C# you would write your example as:
public static class ListExtensions
{
public E Last(this List<E> list)
{
return list[list.Count - 1];
}
}
Using it like this:
List<String> list = new List<String>();
list.Add("test");
Console.WriteLine(list.Last());
So, from a design perspective it can certainly be designed and added. However, there are other considerations that come into play when adding something to an existing language, such as syntax conflicts, backwards compatibility, edge cases, and cost of designing and coding it versus the benefits it provides.
Eric Lippert has a great blog about Extension Properties (a natural extension of Extension Methods) in C#, and in the second part he highlights some of the aspects that affect why doesn't product X have feature Y?, which I'm sure also applies to Java and its development.

C# delegate function implementation in Java [duplicate]

Does the Java language have delegate features, similar to how C# has support for delegates?
Not really, no.
You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).
You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (#blueskyprojects.com)
Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.
Instead of a line like this declaring a named method signature:
// C#
public delegate void SomeFunction();
declare an interface:
// Java
public interface ISomeBehaviour {
void SomeFunction();
}
For concrete implementations of the method, define a class that implements the behaviour:
// Java
public class TypeABehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeA behaviour
}
}
public class TypeBBehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeB behaviour
}
}
Then wherever you would have had a SomeFunction delegate in C#, use an ISomeBehaviour reference instead:
// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();
// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();
With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
...
}
...
SomeMethod(new ISomeBehaviour() {
#Override
public void SomeFunction() {
// your implementation
}
});
This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.
And then of course in Java 8, these do become basically lambda expressions:
// Java 8
SomeMethod(() -> { /* your implementation */ });
Short story: ­­­­­­­­­­­­­­­­­­­no.
Introduction
The newest version of the Microsoft Visual J++ development environment
supports a language construct called delegates or bound method
references. This construct, and the new keywords delegate and
multicast introduced to support it, are not a part of the JavaTM
programming language, which is specified by the Java Language
Specification and amended by the Inner Classes Specification included
in the documentation for the JDKTM 1.1 software.
It is unlikely that the Java programming language will ever include
this construct. Sun already carefully considered adopting it in 1996,
to the extent of building and discarding working prototypes. Our
conclusion was that bound method references are unnecessary and
detrimental to the language. This decision was made in consultation
with Borland International, who had previous experience with bound
method references in Delphi Object Pascal.
We believe bound method references are unnecessary because another
design alternative, inner classes, provides equal or superior
functionality. In particular, inner classes fully support the
requirements of user-interface event handling, and have been used to
implement a user-interface API at least as comprehensive as the
Windows Foundation Classes.
We believe bound method references are harmful because they detract
from the simplicity of the Java programming language and the
pervasively object-oriented character of the APIs. Bound method
references also introduce irregularity into the language syntax and
scoping rules. Finally, they dilute the investment in VM technologies
because VMs are required to handle additional and disparate types of
references and method linkage efficiently.
Have you read this :
Delegates are a useful construct in event-based systems. Essentially
Delegates are objects that encode a method dispatch on a specified
object. This document shows how java inner classes provide a more
generic solution to such problems.
What is a Delegate? Really it is very similar to a pointer to member
function as used in C++. But a delegate contains the target object
alongwith the method to be invoked. Ideally it would be nice to be
able to say:
obj.registerHandler(ano.methodOne);
..and that the method methodOne would be called on ano when some specific event was received.
This is what the Delegate structure achieves.
Java Inner Classes
It has been argued that Java provides this
functionality via anonymous inner classes and thus does not need the additional
Delegate construct.
obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
methodOne(ev);
}
} );
At first glance this seems correct but at the same time a nuisance.
Because for many event processing examples the simplicity of the
Delegates syntax is very attractive.
General Handler
However, if event-based programming is used in a more
pervasive manner, say, for example, as a part of a general
asynchronous programming environment, there is more at stake.
In such a general situation, it is not sufficient to include only the
target method and target object instance. In general there may be
other parameters required, that are determined within the context when
the event handler is registered.
In this more general situation, the java approach can provide a very
elegant solution, particularly when combined with use of final
variables:
void processState(final T1 p1, final T2 dispatch) {
final int a1 = someCalculation();
m_obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
dispatch.methodOne(a1, ev, p1);
}
} );
}
final * final * final
Got your attention?
Note that the final variables are accessible from within the anonymous
class method definitions. Be sure to study this code carefully to
understand the ramifications. This is potentially a very powerful
technique. For example, it can be used to good effect when registering
handlers in MiniDOM and in more general situations.
By contrast, the Delegate construct does not provide a solution for
this more general requirement, and as such should be rejected as an
idiom on which designs can be based.
I know this post is old, but Java 8 has added lambdas, and the concept of a functional interface, which is any interface with only one method. Together these offer similar functionality to C# delegates. See here for more info, or just google Java Lambdas.
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html
No, but they're fakeable using proxies and reflection:
public static class TestClass {
public String knockKnock() {
return "who's there?";
}
}
private final TestClass testInstance = new TestClass();
#Test public void
can_delegate_a_single_method_interface_to_an_instance() throws Exception {
Delegator<TestClass, Callable<String>> knockKnockDelegator = Delegator.ofMethod("knockKnock")
.of(TestClass.class)
.to(Callable.class);
Callable<String> callable = knockKnockDelegator.delegateTo(testInstance);
assertThat(callable.call(), is("who's there?"));
}
The nice thing about this idiom is that you can verify that the delegated-to method exists, and has the required signature, at the point where you create the delegator (although not at compile-time, unfortunately, although a FindBugs plug-in might help here), then use it safely to delegate to various instances.
See the karg code on github for more tests and implementation.
Yes & No, but delegate pattern in Java could be thought of this way. This video tutorial is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces.
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.
static private final Method COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);
...
IoUtil.processDirectory(root,new Callback(this,COUNT),selector);
...
private void callback_count(File dir, File fil) {
if(fil!=null) { // file is null for processing a directory
fileTotal++;
if(fil.length()>fileSizeLimit) {
throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
}
}
progress("Counting",dir,fileTotal);
}
IoUtil.processDirectory():
/**
* Process a directory using callbacks. To interrupt, the callback must throw an (unchecked) exception.
* Subdirectories are processed only if the selector is null or selects the directories, and are done
* after the files in any given directory. When the callback is invoked for a directory, the file
* argument is null;
* <p>
* The callback signature is:
* <pre> void callback(File dir, File ent);</pre>
* <p>
* #return The number of files processed.
*/
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
}
static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
int cnt=0;
if(!dir.isDirectory()) {
if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
}
else {
cbk.invoke(dir,(Object[])null);
File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
if(lst!=null) {
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(!ent.isDirectory()) {
cbk.invoke(dir,ent);
lst[xa]=null;
cnt++;
}
}
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
}
}
}
return cnt;
}
This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.
Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".
It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:
private interface SingleFunc {
void printMe();
}
public static void main(String[] args) {
SingleFunc sf = () -> {
System.out.println("Hello, I am a simple single func.");
};
SingleFunc sfComplex = () -> {
System.out.println("Hello, I am a COMPLEX single func.");
};
delegate(sf);
delegate(sfComplex);
}
private static void delegate(SingleFunc f) {
f.printMe();
}
Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.
With safety-mirror on the classpath you get something similar to C#'s delegates and events.
Examples from the project's README:
Delegates in Java!
Delegate.With1Param<String, String> greetingsDelegate = new Delegate.With1Param<>();
greetingsDelegate.add(str -> "Hello " + str);
greetingsDelegate.add(str -> "Goodbye " + str);
DelegateInvocationResult<String> invocationResult =
greetingsDelegate.invokeAndAggregateExceptions("Sir");
invocationResult.getFunctionInvocationResults().forEach(funInvRes ->
System.out.println(funInvRes.getResult()));
//prints: "Hello sir" and "Goodbye Sir"
Events
//Create a private Delegate. Make sure it is private so only *you* can invoke it.
private static Delegate.With0Params<String> trimDelegate = new Delegate.With0Params<>();
//Create a public Event using the delegate you just created.
public static Event.With0Params<String> trimEvent= new Event.With0Params<>(trimDelegate)
See also this SO answer.
While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.
No, but it has similar behavior, internally.
In C# delegates are used to creates a separate entry point and they work much like a function pointer.
In java there is no thing as function pointer (on a upper look) but internally Java needs to do the same thing in order to achieve these objectives.
For example, creating threads in Java requires a class extending Thread or implementing Runnable, because a class object variable can be used a memory location pointer.
No, Java doesn't have that amazing feature. But you could create it manually using the observer pattern. Here is an example:
Write C# delegate in java
The code described offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:
class Class1 {
public void show(String s) { System.out.println(s); }
}
class Class2 {
public void display(String s) { System.out.println(s); }
}
// allows static method as well
class Class3 {
public static void staticDisplay(String s) { System.out.println(s); }
}
public class TestDelegate {
public static final Class[] OUTPUT_ARGS = { String.class };
public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);
public void main(String[] args) {
Delegate[] items = new Delegate[3];
items[0] = DO_SHOW .build(new Class1(),"show,);
items[1] = DO_SHOW.build (new Class2(),"display");
items[2] = DO_SHOW.build(Class3.class, "staticDisplay");
for(int i = 0; i < items.length; i++) {
items[i].invoke("Hello World");
}
}
}
Java doesn't have delegates and is proud of it :). From what I read here I found in essence 2 ways to fake delegates:
1. reflection;
2. inner class
Reflections are slooooow! Inner class does not cover the simplest use-case: sort function. Do not want to go into details, but the solution with inner class basically is to create a wrapper class for an array of integers to be sorted in ascending order and an class for an array of integers to be sorted in descending order.

Is it possible to override a method at runtime?

Is there anyway to override a method at run time? Even if it requires dynamically creating a subclass from that instance?
With plain Java, no.
With ByteBuddy(preferred), asm, cglib or aspectj, yes.
In plain Java, the thing to do in a situation like that is to create an interface-based proxy that handles the method invocation and delegates to the original object (or not).
You could create an anonymous class that overrides the method and uses the strategy pattern to decide what to do.
If you are looking for dynamic compilation from code, you can follow these instructions
As others said, no, you can't override a method at runtime. However, starting with Java 8 you can take the functional approach. Function is a functional interface that allows you to treat functions as reference types. This means that you can create several ones and switch between them (dynamically) a-la strategy pattern.
Let's look at an example:
public class Example {
Function<Integer, Integer> calculateFuntion;
public Example() {
calculateFuntion = input -> input + 1;
System.out.println(calculate(10));
// all sorts of things happen
calculateFuntion = input -> input - 1;
System.out.println(calculate(10));
}
public int calculate(int input) {
return calculateFuntion.apply(input);
}
public static void main(String[] args) {
new Example();
}
}
Output:
11
9
I don't know under what circumstances and design you intend to override, but the point is that you replace the behavior of the method, which is what overriding does.
I think it not possible with simple Java.
With reflection and/or cglib probally you can do it.
Look at these links:
http://www.rgagnon.com/javadetails/java-0039.html
http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html

Categories