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.
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.
MethodType object can be created via special factory using the following method:
2) The next transitional state is getting lookup object which helps us to find appropriate method in a target class.
3) Invoke your method
- it has full access to all methods allowed in a current context
- works faster (in some conditions)
The last argument sometimes may be sufficient, for some projects that should use reflection repeatedly. Performance of MethodHandle depends on the way you are using it. In some cases Reflection API shows better results.
There are some links to get more information about MethodHandle performance.