Tuesday, October 28, 2014

Initialize object with Java reflection mechanism

Java 7 has an improved way of working with object's reflection in comparison with older versions.
For example, at version 6 in order to initialize object and its fields we need.
1) initialize class object instance using type name of the target object
2) if some object's methods (for example 'setXxx') should be invoked, need to find it and pass corresponding parameters - be aware of parameter type, it must me consistent with original method signature.

Object param = new SomeType(); // SomeType must be included in a signature of the target method 
String type = "com.vbashur.MyType"
Class<?> clazz = Class.forName(type);
Object paramObject = clazz.newInstance();
String setterName = "setMyValue"

for (Method m : clazz.getDeclaredMethods()) { // if parameters are known, use getDeclaredMethod
    if (m.getName().equals(setterName)) {
        m.invoke(paramObject, param);

The piece of code above may throw a bunch of ugly exceptions (llegalAccessException,
IllegalArgumentException, InvocationTargetException, InstantiationException, ClassNotFoundException) and works quite slow. In order to access private method it requires Method.setAccessible() to be invoked.

MethodHandle is a Java-7-way

1) What we need to do is to declare MethodType object firstly. A MethodType is an immutable object that represents the type signature of a method.

Friday, October 3, 2014

Merge Sort in Java (+JavaScript)

Merge sort algorithm has a worst-case performance of O(n log n) - that's a good performance of comparison-based sorting algorithm, moreover this algorithm is easy to understand, remember and repeat after while.
For implementation I'm going to use mergeSort method with the following signature:
<T extends Comparable<T>> void mergeSort(T[] arrayToSort, T[]resArray)
arrayToSort - array to be sorted
resArray - empty array with the same length as arrayToSort which will have all arrayToSort's items in a sorted order

In step one of merge sort we need to copy the content of arrayToSort into resArray and specify array's start and end indicies.

int lo = 0;
int hi = arrayToSort.length - 1;
for (int iter = 0; iter < arrayToSort.length; ++iter) {
 resArray[iter] = arrayToSort[iter];

Now it's time to split an array in a central element and get two subarrays
int mid = lo + (hi - lo) / 2; // this is a central element index of array
1-st subarray elements will be from lo to mid indicies
2-nd subarray elements will be from mid + 1 to hi indicies

The following function can break up into subarrays recursively:

<T extends Comparable<T>> void sortMerge(T[] arrayToSort, T[] resArray, int lo, int hi) {
    if (lo >= hi)
 int mid = lo + (hi - lo) / 2;
 sortMerge(arrayToSort, resArray, lo, mid);
 sortMerge(arrayToSort, resArray, mid + 1, hi);
 //merge(arrayToSort, resArray, lo, mid, hi);