| This utility class greatly facilitates the use of reflection to invoke
constructors or methods which may or may not exist at runtime.
The constructors/methods are identified through their signatures
represented as a
String . When the constructor/method does
not exist (e.g. class not found) or when the platform does not support
reflection, the constructor/method is null
(no exception raised). Here is an example of timer taking advantage
of the new (JRE1.5+) high resolution time when available:[code]
public static long microTime() {
if (NANO_TIME_METHOD != null) { // JRE 1.5+
Long time = (Long) NANO_TIME_METHOD.invoke(null); // Static method.
return time.longValue() / 1000;
} else { // Use the less accurate time in milliseconds.
return System.currentTimeMillis() * 1000;
}
}
private static final Reflection.Method NANO_TIME_METHOD
= Reflection.getMethod("j2me.lang.System.nanoTime()");[/code]
Arrays and primitive types are supported. For example:[code]
Reflection.Constructor sbc = Reflection.getConstructor("j2me.lang.StringBuilder(int)");
if (sbc != null) { // JDK 1.5+
Object sb = sbc.newInstance(new Integer(32));
Reflection.Method append = Reflection.getMethod("j2me.lang.StringBuilder.append(char[], int, int)");
append.invoke(sb, new char[] { 'h', 'i' }, new Integer(0), new Integer(2));
System.out.println(sb);
}
> hi[/code]
author: Jean-Marie Dautelle version: 4.0, September 1, 2006 |