Change Method Call On the Fly:: CallSite

In my previous article, I talked about invokeDynamic, In this article, I will show you the coding how you can leverage the power of invokedynamic.
We all know that to load a class dynamically and call a method at runtime we use Java Reflection, Framework developers are often used Reflection to load class runtime and call a method at runtime. But Reflection has a performance cost as it does the security checking each time, On the other hand, invokeDynamic solves that problem and we can use invokeDynamic to runtime call the method.
To call the method runtime we need Method handle, Mow the interesting thing is we also change the underlying method call based on some parameters, It is a very powerful thing to do, the Same call can invoke different implementation on runtime based on parameter !!!

I try to explain you by a simple example, Say there are two methods call bark and mewaoo, Now based on the animal passed I want to call the corresponding method dynamically?
I will show you the code first then explain the code,
package com.example.methodhandle;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
public class MethodHandleExample {
MutableCallSite callSite = null;
public void bark() {
System.out.println("I am a Dog :: So barking");
}
public void mewaoo() {
System.out.println("I am a Cat :: So Mewaooing");
}
public MethodHandle findMethodHandle(String command) throws NoSuchMethodException, IllegalAccessException {
MethodHandle mh = null;
if ("DOG".equalsIgnoreCase(command)) {
mh = createMethodHandle(MethodType.methodType(void.class), "bark");
} else if ("CAT".equalsIgnoreCase(command)) {
mh = createMethodHandle(MethodType.methodType(void.class), "mewaoo");
} else {
throw new RuntimeException("Give a Proper Command");
}
return mh;

}

public CallSite createCallSite(String command) throws NoSuchMethodException, IllegalAccessException {
if (callSite == null) {
callSite = new MutableCallSite(findMethodHandle(command));
} else {
callSite.setTarget(findMethodHandle(command));
}
return callSite;
}

public MethodHandle createMethodHandle(MethodType methodType, String methodName)
throws NoSuchMethodException, IllegalAccessException {
return MethodHandles.lookup().findVirtual(this.getClass(), methodName, methodType);
}
public static void main(String[] args) {
MethodHandleExample example = new MethodHandleExample();
try {
example.createCallSite("DOG").dynamicInvoker().invoke(example);
example.createCallSite("CAT").dynamicInvoker().invoke(example);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If I run this code output will be
I am a Dog :: So barking
I am a Cat :: So Mewaooing
Explanation:: To call bark and mewaoo method dynamically based on the passing parameter, We first need to create  MethodHandle for each method.
MethodHandle is such an Object which stores the metadata about the method, Such as the name of the method signature of the method etc.
So here, I create a generic method called createMethodHandle, which returns a method handle.
To create a Method handle we need two major thing name of the method and the MethodType Object, MethodType Object says about the signature of the method. name parameter denotes the name of the method.
I create a generic method called findMethodHandle, This method passes the required parameters to the createMethodHandle method based on the passed command, If the command is a dog, this method pass the method name as bark and method type as void as bark takes nothing and return nothing (Signature of bark method).
Now , to change the invocation of the method we need a Calliste --Which actually flips the call, For two methods we have two different method handle, Calliste bound with a Method handle and  actually call underlying  Method handle , MutableCallsite can change the underlying Method handle Object (Strategy), so Callsite change the MethodHandle based on the command given.
Here I create a method called createCallSIte, which create a single instance of a Callsite Object, and based on the command, Callsite change the target aka MethodHandle.

Conclusion: This is a simple example but using Callsite and Methodhandle you can create a factory of Strategy and based on the situation you can choose the optimum one, so developers perspective it just a method call but ad framework developer you can choose what to call when like lambda in java8 maintained LambdaMewtaFactory.




Overriding in Java in context of design.


Overriding in Java in context of design.

 


 While you are going for an Interview for a Lead or Developer role. The interviewer will definitely ask you some questions on Overriding and try to puzzle you.


In this tutorial, I try to cover all topics of Overriding so you feel comfortable and easily answer  whatever questions they ask


Definition of Overriding:
In Java, Overriding is a technique by which parent class delegates responsibility to Child. A child can define child specific behavior which will be executed at run time.

From the above definition, it is clear that to do Overriding Parent class and child class is must need, without Child class, we can't achieve overriding, unlike overloading.

Please remember , The interviewer may ask you-- can it be possible to do overriding without child class?

As I said child specific behavior executed at run-time what I mean by this is the  JVM will decide which  Subclass/Object's method it has to call,  so we call it late binding or Dynamic method dispatch.Because runtime JVM decides what to do not at compile time.

Question: What is late binding/ Dynamic method dispatch in Java

If you don't get my point don't worry follow example will clear the concept.



Before dig down to Overriding details let clear one small thing.


The big power of OOP programming is it supports Polymorphic assignment where a parent class reference can point a Subclass object. It will be heavily used in Design pattern or I can say the Whole Design pattern is based on this small concept.

 

Q: What do you mean by polymorphic assignment and Why it is important?


Let's understand why this is important.


say  Foo is Parent class and Bar is child class so we can do that,


Foo foo = new Bar();//Polymorphic assignment.

By parent reference, we can point child Object. It is logical as child inherited all properties of the parent so whatever in parent must have in the child unless properties are private in a parent.


What is the benefits of polymorphic assignment?
 let see the small code

Class Power
{

private Foo f;

public setFoo(Foo f)
{
this.f = f;

}

public void show()
{
f.print();
}
}

Class Foo has a print() method which is overridden in Bar and Zoo two subclasses of Foo

overridden  in Bar
public void print()
{
Sysout(“Bar”);
}


overridden in Zoo
public void print()
{
sysout(“Zoo”);
}

overriding java


so by the setFoo method in Power class, I can easily set Bar or Zoo instance at run time based on some business logic .so when it calls show method based on the subclass it prints Bar or Z

So I can easily change the behavior of the Power class on the fly based on strategy. It is the crux of Strategy design pattern.

But remember, As SetFoo method takes parent reference what ever method are in parent class  you can call those, all Association condition applied here. So if any new method added in subclass that is not visible by parent reference.

Qustion : expect a coding snippet here where interviewr add a method in child and try to call it by polymorphic refrence.

To make it visible you need to do down-casting.

Tip: Always use @Override annotation if you are using Java 5 or more to make sure if maintains all rules of overriding.


To do a perfect overriding we have to follow some rules.

The method which will be overridden must have same data signature also return type will be same

but onwards java 1.5 return type can be subclasses of parent type we say it Co-variant return.
 Q: What is covarient return?


Please follow the following contracts and burn it into the head as in Interview or in Exam you can found various types of combination and you have to find the perfect overridden method.
1. The argument list must exactly match that of the overridden method. If they
don't match, you can end up with an overloaded method .


2. The return type must be the same as, or a subtype of, the return type declared
in the original overridden method in the superclass. we say it covariant return


3. The access level can't be more restrictive than the overridden methods.
The access level CAN be less restrictive than that of the overridden method.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override
any superclass method that is not marked private or final. A subclass in a
different package can override only those non-final methods marked public
or protected (since protected methods are inherited by the subclass).

4. The overriding method CAN throw any unchecked (runtime) exception,
regardless of whether the overridden method declares the exception.

5. The overriding method must NOT throw checked exceptions that are new
or broader than those declared by the overridden method. For example, a
the method that declares a FileNotFoundException cannot be overridden by a
the method that declares an SQLException, Exception, or any other non-runtime
exception unless it's a subclass of FileNotFoundException.

6. The overriding method can throw narrower or fewer exceptions.

Understand protected modifier in java

Understanding most critical access modifier  protected in java?


We all know Java has three access modifiers a, public b. protected c. private and four access levels  a.public b. protected c. private d. default among them protected is the most critical modifier to understand.


Definition of protected
protected is same as default modifier, which can be accessed by other classes in the same package but the only difference is it can also be accessed by sub classes from outside packages through inheritance.

Now there are two catch points

1. What do you mean by accessed?
2. What do you mean by access through inheritance?

1. What do you mean by accessed?


In Java, we can access properties of other classes by two ways

a. Association (HAS A)
b. Inheritance (IS-A)

Scenario a.

package com.bar;
public class Bar
{
 protected String greet = "Hello";
}



package com.foo;
public class Foo extends Bar
{
Bar bar = new Bar(); // Bar HAS A relationship with Foo(Association)

bar.greet; //not compiled as no visibility through association

}



Scenario b

package com.bar
Class Bar
{
 protected String greet = "Hello";
}


package com.foo
Class Foo extends Bar
{


System.out.println(greet); //accessd through Inheritence so it prints Hello

}



Association means a class has a reference to another class  as you see in Scenario a.

Inheritance means  a class inheriting parent class property.
The Answer is  no as by rule protected is visible only through inheritance so although class Foo extends Bar but we are trying to access greet variable through association which is not acceptable in Java



On another hand, in Scenario 2 will compile fine and show Hello as Foo inherited Bar's greet property though Inheritance by definitions which is acceptable.

Now, adding bit complexity in it
suppose,
the class zoo is in the package com.foo now If I write following code snippet in Zoo


Foo foo = new Foo();
foo.greet;

will it be compile?

Think about it.......

The Answer is no as I said earlier by Association (different package ) you can't ever access greet. but in Same package you do.

See the relationship picture to remember the rule.

Protected access modifiers