Java Reference
In-Depth Information
}
}
RememberingList hList = new RememberingList ();
List < String > l =
( List < String >) Proxy . newProxyInstance ( List . class . getClassLoader (),
new Class [] { List . class },
hList );
l . add ( "cat" );
l . add ( "bunny" );
l . clear ();
System . out . println ( l );
Proxies are an extremely powerful and flexible capability that are used within many
Java frameworks.
Method Handles
In Java 7, a brand new mechanism for introspection and method access was intro‐
duced. This was originally designed for use with dynamic languages, which may
need to participate in method dispatch decisions at runtime. To support this at the
JVM level, the new invokedynamic bytecode was introduced. This bytecode was not
used by Java 7 itself, but with the advent of Java 8, it was extensively used in both
lambda expressions and the Nashorn JavaScript implementation.
Even without invokedynamic , the new Method Handles API is comparable in power
to many aspects of the Reflection API—and can be cleaner and conceptually simpler
to use, even standalone. It can be thought of as Reflection done in a safer, more
modern way.
MethodType
In Reflection, method signatures are represented as Class[] . This is quite cumber‐
some. By contrast, method handles rely on MethodType objects. These are a typesafe
and object-orientated way to represent the type signature of a method.
They include the return type and argument types, but not the receiver type or name
of the method. The name is not present as this allows any method of the correct sig‐
nature to be bound to any name (as per the functional interface behavior of lambda
expressions).
A type signature for a method is represented as an immutable instance of Method
Type , as acquired from the factory method MethodType.methodType() . For exam‐
ple:
MethodType m2Str = MethodType . methodType ( String . class ); // toString()
// Integer.parseInt()
MethodType mtParseInt =
MethodType . methodType ( Integer . class , String . class );
Search WWH ::




Custom Search