java - Runtime delegation of unknown method calls -
background
consider objects alice, bob, , eve. in smalltalk, alice can send message bob bob delegates eve, without bob knowing name of method delegate (see smalltalk delegation of unknown method call).
problem
java can partially emulate smalltalk's behaviour coding alice like:
public void methodname() { object bob = new bob(); try { ((bobinterface)bob).methodname(); } catch( classcastexception e ) { ((bobinterface)bob).doesnotunderstand( new method( name ) ); } }
this captures intent, verbose , repetitious (being codified once per method). can impractical if code generated.
java 8 introduces lambda expressions (see so answer).
question
how codify bob such method invocations bob not implement passed alice eve via bob?
for example, variation of following should display received alice's message!
:
public class alice { public static void main( string args[] ) { bob bob = new bob(); // problematic line... bob.listen(); } } public class bob { private eve eve; // when "bob.listen()" called, should invoked... public void doesnotunderstand( method m ) { delegate( eve, m ); } } public class eve { public void listen() { system.out.println( "received alice's message!" ); } }
problem constraints
- lambda expressions, reflection, or both welcome.
- third-party libraries (e.g., bytecode manipulation) , aspects not ideal.
- bob can not implement more 1 method nor inherit methods.
- neither alice nor bob should contain repetitious code.
ideas
method names can retrieved implementing local classes:
public class t { public static void main( string args[] ){ class local {}; string name = local.class.getenclosingmethod().getname(); system.out.printf( "%s%n", name ); } }
related
i don't think possible @ runtime. code compile, @ least need interface "understands" methods. sure can use reflection , invoke dynamically lose type safety. way see working use kind of (precompile) code generation (you use standard java annotations if dont want rely on third party libraries).
Comments
Post a Comment