Recently I have been introduced to a lot of “REAL” JavaScript and it would not be wrong to say that I am in love with JavaScript. Also, while coding in JavaScript, I have got into the habit of comparing it with Java (which i have been using since i started my professional career).

A few days back, I wrote a small script which needed to be used in three or four web pages and each time the script was called (on some browser event) I had to execute some other function conditionally i.e if the function being called was defined. In each of the web pages only the other function to be called was different, the rest of the functionality remained the same.

Eg:

function foo() {

//The conditional method calling part – START
if (self.bar) {

bar();

}

if (self.moo) {

moo();

}

.
.
.
.
.
.
//The conditional method calling part – END

//The common functionality – START

//The common functionality – END

}

The above script checks as to whether a function bar is defined and if so calls it. Same with function moo. As you can see in JavaScript checking whether a function has been defined is as simple as saying self(or window).functionName.

Q: How can we do something similar in Java (I have never come across a scenario where I had to do this in Java)?

Ans: Using reflection.

Below code calls the method foo if it is present, else NoSuchMethodException is thrown.

public class MethodChk {

public void foo() {

System.out.println(“foo”);

}

public void bar() {

System.out.println(“bar”);

}

public static void main(String[] args) throws IllegalAccessException,

InvocationTargetException {

MethodChk methodChk = new MethodChk();
Class clz = methodChk.getClass();
try {

Method method = clz.getMethod(“foo”, new Class[] {});
method.invoke(new MethodChk(), new Object[] {});

} catch (NoSuchMethodException nsme) {

nsme.printStackTrace();

}
}

}
Java code becomes a bit clunky as Java does not treat functions as first class citizens. JavaScript does.

Advertisements