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); break; } }
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.