I would like to use JRuby to change the behavior of a Java class already
deployed in a JVM by overriding its methods and inserting my own JRuby
code
in its place. (FWIW, I am really trying to override the method of a
class
that implements an interface.) This class is invoked directly by other
Java
classes that I don’t have access to, so I can’t force them to call a
JRuby
class instead.
Is there a way for me to intercept the call to a Java method using
JRuby?
I’m pretty sure this can be done when the method is called by another
JRuby
class, but I’m wondering if it can be done when it’s a Java class
calling
the Java method.
Do I need to use AOP for this, or is there any way to do this in JRuby?
JRuby
Do I need to use AOP for this, or is there any way to do this in
JRuby?
Thanks,
Lee
Are you talking about providing a subclass of the Java class, then
override methods that can be called polymorphically? That’s pretty
easy to do.
If you’re talking about re-opening a class and adding new methods,
those methods will only be visible/usable on JRuby’s end, even if the
Java method already existed.
Neither, really. I’m really talking about redefining the method of an
existing Java class. It’s not a subclass, and it’s not new methods.
It’s a
redefinition of a method, and it has to be accessible from the Java
side. I
think AOP (or some other form of bytecode manipulation) is the only way
to
do this.
It’s a redefinition of a method, and it has to be accessible from the Java
side. I think AOP (or some other form of bytecode manipulation) is the only
way to do this.
You are right. Java classes can’t be actually redefined once they are
loaded. You must use some bytecode manipulation through class
instrumentation or load the classes with a custom classloader that
inserts
the required bytecode.
Any methods defined on the Ruby-side for a Java class won’t be seen on
the Java side. Redefining a method means you provide a new one that
just happens to stomp the old one.
I’m not familiar with the library you’re interfacing with, but chances
are a Ruby subclass of a Java class would be the easiest thing to do,
provided you can get the library to use that subclass.