Is there any technique available in Java for intercepting messages (method calls) like the method_missing technique in Ruby? This would allow coding decorators and proxies very
easily, like in Ruby:
:Client p:Proxy im:Implementation
------- ---------- -----------------
p.foo() -------> method_missing()
do_something
im.foo() ------------------> do_foo
p.bar() --------> method_missing()
do_something_more
im.bar() -------------------> do_bar
(Note: Proxy only has one method: method_missing())
As others have correctly said already, use a DynamicProxy. Here's an example.
This class uses a DynamicProxy to intercept invocations of methods declared in the "HammerListener" interface. It does some logging and then delegates to the "real" HammerListener implementation (yes, the same thing can be done with AOP).
See the newInstance method for proxy instantiation (note that you need to pass in the interface(s) the proxy should implement - a proxy can implement multiple interface).
All method invocations on interfaces that the proxy implements will end up as calls to the "invoke" method, which is declared in the "InvocationHandler" interface. All proxy handlers must implement this interface.
import java.lang.reflect.*;
/**
* Decorates a HammerListener instance, adding BEFORE/AFTER
* log messages around all methods exposed in the HammerListener interface.
*/
public class HammerListenerDecorator implements InvocationHandler {
private final HammerListener delegate;
static HammerListener newInstance(HammerListener delegate) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return (HammerListener)Proxy.newProxyInstance(cl, new Class[]{HammerListener.class},
new HammerListenerDecorator(delegate));
}
private HammerListenerDecorator(HammerListener delegate) {
this.delegate = delegate;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
logger.info("BEFORE " + method.getName() + " {{{" + argsToString(args) + "}}}");
Object rtn = method.invoke(delegate, args);
logger.info("AFTER " + method.getName());
return rtn;
}
private String argsToString(Object[] args) {
StringBuilder sb = new StringBuilder();
for (Object o : args) {
sb.append(String.valueOf(o)).append(" ");
}
return sb.toString();
}
}
java.lang.reflect.Proxy is the starting point for generating runtime proxies for interfaces you specify at runtime. It allows you to specify the interface to be proxied, as well as the object that handles the "real" invocation which, if you choose, can of course simply call something else.
The output of the Proxy class is an object that you can cast to your desired interface type, and use and invoke like any other object.
It's not going to be as easy as with a dynamic language like Ruby, but you pay a price for a strongly static language like Java.
See java.lang.reflect.Proxy and java.lang.reflect.InvocationHandler or Aspect-oriented programming in general (AspectJ for instance).
Not exactly. The closest equivalent is a Dynamic Proxy object, but that has some limitations (ie, it can only be called through reflection).
Related
What is the purpose of java.lang.reflect.Proxy and java.lang.reflect.InvocationHandler?
when we need to create and use these on our application?
Proxy is a design pattern. We create and use proxy objects when we want to add or modify some functionality of an already existing class. The proxy object is used instead of the original one. Usually, the proxy objects have the same methods as the original one and in Java proxy classes usually extend the original class. The proxy has a handle to the original object and can call the method on that.
This way proxy classes can implement many things in a convenient way:
logging when a method starts and stops
perform extra checks on arguments
mocking the behavior of the original class
access to costly resources
Without modifying the original code of the class. (The above list is not extensive, it only list some examples).
To create an actual dynamic proxy class, all you need to do is implement the java.lang.reflect.InvocationHandler interface:
public Class MyDynamicProxyClass implements
java.lang.reflect.InvocationHandler
{
Object obj;
public MyDynamicProxyClass(Object obj)
{ this.obj = obj; }
public Object invoke(Object proxy, Method m, Object[] args) throws
Throwable
{
try {
// do something
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw e;
}
// return something
}
}
That's all there is to it!Okay, well, you also have to have your actual proxy interface:
public interface MyProxyInterface
{
public Object MyMethod();
}
Then to actually use that dynamic proxy, the code looks like this:
MyProxyInterface foo = (MyProxyInterface)
java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
Class[] { MyProxyInterface.class },
new MyDynamicProxyClass(obj));
Knowing that the above code is just horribly ugly, I'd like to hide it in some type of factory method. So instead of having that messy code in the client code, I'll add that method to my MyDynamicProxyClass:
static public Object newInstance(Object obj, Class[] interfaces)
{
return
java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
interfaces,
new
MyDynamicProxyClass(obj));
}
That allows me to use the following client code instead:
MyProxyInterface foo = (MyProxyInterface)
MyDynamicProxyClass.newInstance(obj, new Class[]
{ MyProxyInterface.class });
That is much cleaner code. It might be a good idea in the future to have a factory class that completely hides the entire code from the client, so that the client code looks more like:
MyProxyInterface foo = Builder.newProxyInterface();
Overall, implementing a dynamic proxy is fairly simple.
Ref :
https://dzone.com/articles/java-dynamic-proxy
https://www.javaworld.com/article/2076233/java-se/explore-the-dynamic-proxy-api.html
I would like to write a generic algorithm, which can be instantiated with different objects. The objects are coming from 3rdparty and they have no common base class. In C++, I just write the generic algorithm as a template which takes the particular object as its argument. How to do it in Java?
template <class T>
class Algorithm
{
void Run(T& worker)
{
...
auto value = workder.DoSomething(someArgs);
...
}
};
In C++, I don't need to know anything about the T, because the proper types and availability of methods are checked during compilation. As far as I know,
in Java I must have a common base class for all my workers to be able to call methods on them. Is it right? Is there a way how to do similar stuff in Java?
I can't change my 3rdparty workers, and I don't want to make my own abstraction of all workers (including all types which the workers are using, etc.).
Edit:
Since I want to write the generic algorithm only once, maybe it could be a job for some templating language which is able to generate Java code (the arguments to the code template would be the workers)?
My solution:
In my situation, where I cannot change the 3rdparty workers, I have chosen Java code generation. I have exactly the same algorithm, I only need to support different workers which all provides identical interface (classes with same names, same names of methods, etc.). And in few cases, I have to do a small extra code for particular workers.
To make it more clear, my "workers" are in fact access layers to a proprietary DB, each worker for a single DB version (and they are generated).
My current plan is to use something like FreeMaker to generate multiple Java source files, one for each DB version, which will have only different imports.
The topic to look into for you: generics
You can declare a class like
public class Whatever<T> {
which uses a T that allows for any reference type. You don't need to further "specialize" that T mandatorily. But of course: in this case you can only call methods from Object on instances of T.
If you want to call a more specific method, then there is no other way but somehow describing that specification. So in your case, the reasonable approach would be to introduce at least some core interfaces.
In other words: there is no "duck typing" in Java. You can't describe an object by only saying it has this or that method. You always need a type - and that must be either a class or an interface.
Duck typing isn't supported in Java. It can be approximated but you won't get the convenience or power you're used to in C++.
As options, consider:
Full-on reflection + working with Object - syntax will be terrible and the compiler won't help you with compilation checks.
Support a pre-known set of types and use some sort of static dispatching, e.g a big switch / if-else-if block, a type -> code map, etc. New types will force changing this code.
Code generation done during annotation processing - you may be able to automate the above static-dispatch approach, or be able to create a wrapper type to each supported type that does implement a common interface. The types need to be known during compilation, new types require recompilation.
EDIT - resources for code generation and annotation processing:
Annotation processing tutorial by #sockeqwe
JavaPoet, a clean code generation tool by Square
If you really don't have any way to get it done correctly with generics you may need to use reflection.
class A {
public String doIt() {
return "Done it!";
}
}
class B {
public Date doIt() {
return Calendar.getInstance().getTime();
}
}
interface I {
public Object doIt();
}
class IAdapter implements I {
private final Object it;
public IAdapter(Object it) {
this.it = it;
}
#Override
public Object doIt() {
// What class it it.
Class<?> itsClass = it.getClass();
// Peek at it's methods.
for (Method m : itsClass.getMethods()) {
// Correct method name.
if (m.getName().equals("doIt")) {
// Expose the method.
m.setAccessible(true);
try {
// Call it.
return m.invoke(it);
} catch (Exception e) {
throw new RuntimeException("`doIt` method invocation failed", e);
}
}
}
// No method of that name found.
throw new RuntimeException("Object does not have a `doIt` method");
}
}
public void test() throws Exception {
System.out.println("Hello world!");
Object a = new IAdapter(new A()).doIt();
Object b = new IAdapter(new B()).doIt();
System.out.println("a = "+a+" b = "+b);
}
You should, however, make every effort to solve this issue using normal type-safe Java such as Generics before using reflection.
In Java all your Workers must have a method DoSomething(someArgs), which doesn't necessarily imply that they extend the same base class, they could instead implement an interface Worker with such a method. For instance:
public interface Worker {
public Double DoSomething(String arg1, String arg2);
}
and then have different classes implement the Worker interface:
One implementation of Worker:
public class WorkerImplA implements Worker{
#Override
public Double DoSomething(String arg1, String arg2) {
return null; // do something and return meaningful outcome
}
}
Another implementatin of Worker:
public class WorkerImplB implements Worker{
#Override
public Double DoSomething(String arg1, String arg2) {
return null; // do something and return meaningful outcome
}
}
The different WorkerImpl classes do not need to extend the same common base class with this approach, and as of JavaSE 8 interfaces can have a default implementation in any method they define.
Using this approach Algorithm class would look like:
public class Algorithm {
private String arg1;
private String arg2;
public Algorithm(String arg1, String arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}
public void Run(Worker worker){
worker.DoSomething(arg1, arg2);
}
}
I am trying to port an SDK written in java to C#.
In this software there are many "handler" interfaces with several methods (for example: attemptSomethingHandler with success() and several different failure methods). This interface is then implemented and instantiated anonymously within the calling class and passed to the attemptSomething method of the SomethingModel class. This is an async method and has several places where it could fail or calls another method (passing on the handler). This way, the anonymous implementation of attemptSomethingHandler can reference private methods in the class that calls attemptSomething.
In C# it is not possible to anonymously implement an interface. I could explicitly implement a new class, but this implementation would be unique to this calling class and not used for anything else. More importantly, I would not be able to access the private methods in the calling class, which I need and do not want to make public.
Basically, I need to run different code from the calling class depending on what happens in the SomethingModel class methods.
I've been reading up on delegates but this would require passing as many delegates as there are methods in the handler interface (as far as I can tell).
What is the appropriate way to do this in C#? I feel like I'm missing out on a very common programming strategy. There simply must be an easy, clean way to structure and solve this problem.
Using delegates:
void AttemptSomethingAsync(Action onSuccess, Action<string> onError1, Action onError2 = null) {
// ...
}
// Call it using:
AttemptSomethingAsync(onSuccess: () => { Yes(); }, onError1: (msg) => { OhNo(msg); });
Or, using a class
class AttemptSomethingHandler {
Action OnSuccess;
Action<string> OnError1;
Action OnError2;
}
void AttemptSomethingAsync(AttemptSomethingHandler handler) {
// ...
}
// And you call it like
AttemptSomethingAsync(new AttemptSomethingHandler() {
OnSuccess = () => { Yes() };
});
Or events
public delegate void SuccessHandler();
public delegate void ErrorHandler(string msg);
class SomethingModel {
public event SuccessHandler OnSuccess;
public event ErrorHandler OnError1;
public void AttemptSomethingAsync() {
// ...
}
}
// Use it like
var model = new SomethingModel();
model.OnSuccess += Yes;
model.AttemptSomethingAsync();
private void Yes() {
}
In C#, we don't have anonymous types like Java per se. You can create an anonymous type which contains fields like so:
var myObject = new { Foo = "foo", Bar = 1, Quz = 4.2f }
However these cannot have methods placed in them and are only passable into methods by use of object or dynamic (as they have no type at compile-time, they are generated by the compiler AFAIK)
Instead in C# we use, as you said, delegates or lambdas.
If I understand your pickle correctly, you could implement a nested private class like so:
interface IMyInterface
{
void Foo();
}
class MyClass
{
public void Bar()
{
var obj = new MyInterface();
obj.Foo();
}
private class MyInterface : IMyInterface
{
public void Foo()
{
// stuff
}
}
}
Now MyClass can create an instance of MyInterface which implements IMyInterface. As commentors have mentioned, MyInterface can access members of MyClass (although you most certainly want to try and stick to using publicly accessible members of both types).
This encapsulates the "anonymous" class (using Java terms here to make it simpler) and also means that you could potentially return MyInterface as an IMyInterface and the rest of the software would be none the wiser. This is actually how some abstract factory patterns work.
Basically, I need to run different code from the calling class depending on what happens in the SomethingModel class methods.
This smells of heavy coupling. Oh dear!
It sounds to me like your particular problem could use refactoring. In C# you can use Events to solve this (note: Can, not should). Just have an Event for each "branch" point of your method. However I must say that this does make your solution harder to envisage and maintain.
However I suggest you architect your solution in a way such that you don't need such heavy coupling like that.
You could also try using a Pipeline model but I'm not sure how to implement that myself. I know that jetty (or is it Netty? the NIO for Java by JBOSS) certainly used a similar model.
You may find that throwing out some unit tests in order to test the expected functionality of your class will make it easier to architect your solution (TDD).
You can use nested classes to simulate anonymous classes, but in order to use nested classes in the same way as Java you will need to pass a reference to the outer class. In Java all nested and anonymous classes have this by default, and only static ones do not.
interface IMyInterface
{
void Foo();
}
class MyClass
{
public void Bar()
{
IMyInterface obj = new AnonymousAnalog(this);
obj.Foo();
}
private class AnonymousAnalog : IMyInterface
{
public void Foo(MyClass outerThis)
{
outerThis.privateFieldOnOuter;
outerThis.PrivateMethodOnOuter();
}
}
...
}
I´ve read 'C# anonymously implement interface (or abstract class)' thread for implementing an interface anonymously. But I wondered if this is also possible using .NET 2.0 (NO LINQ) using delegates or any similar approach. I know from JAVA the following possible:
MyClass m = MyMethod(new MyInterface() {
#override
public void doSomething() {...}
}
(I hope I remember well, is a time ago that I used JAVA, but I suppose it was something similar). This might be helpful whenever a method needs an instance of an interface and is called only once so there is no need to create a new class for this single approach.
.NET 2.0 also supported anonymous delegates, it's just that the syntax was a bit more verbose compared to lambdas, and type inference didn't work. And there were no extension methods in C# 2.0 (although you were able to use C# 3.0 and compile against .NET 2.0), which are the basis of LINQ and being able to operate on interfaces.
Compare:
.NET 2.0: delegate(int i) { return (i < 5); }
.NET 3.5: i => i < 5
.NET 2.0 also lacks common generic delegate signatures (Func and Action), but you can also easily define them yourself (for all combinations of parameters you like):
public delegate void Action<T>(T item);
public delegate Tresult Func<T, Tresult>(T item);
So, whatever approach your linked answer used to mimic anonymous interfaces can be represented using .NET 2.0 delegates, at the expense of added verbosity. Making you ask yourself: "is this really that shorter to write?"
[Update]
If your interface is a single method interface, like:
interface IFoo
{
string Bar(int value);
}
class SomeOtherClass
{
void DoSomething(IFoo foo);
}
then you might get rid of it entirely and simply use a delegate instead:
class SomeOtherClass
{
void DoSomething(Func<int, string> bar);
}
new SomeOtherClass().DoSomething(delegate(int i) { return i.ToString(); });
If you have an interface with many methods that you want to be able to implement inline in many different places, you can use something like this:
interface IFoo
{
string GetSomething();
void DoSomething(int value);
}
// conditional compile, only if .NET 2.0
#if NET_2_0
public delegate void Action<T>(T item);
public delegate Tresult Func<Tresult>();
#endif
class DelegatedFoo : IFoo
{
private readonly Func<string> _get;
private readonly Action<int> _do;
public DelegatedFoo(Func<string> getStuff, Action<int> doStuff)
{
_get = getStuff;
_do = doStuff;
}
#region IFoo members simply invoke private delegates
public string GetSomething()
{ return _get(); }
public void DoSomething(int value)
{ _do(value); }
#endregion
}
Which would allow you to pass delegates to the DelegatedFoo class inline:
var delegated = new DelegatedFoo(
delegate() { return ""; }, // string GetSomething()
delegate(int i) { } // void DoSomething(int)
);
Using .NET 4 the C# 4.0 syntax it would look a bit cleaner due to syntactic sweetness of lambdas and named parameters:
var delegated = new DelegatedFoo(
getStuff: () => "",
doStuff: i => { }
);
I know that this may not be exactly what you are hoping for, but if you absolutely have to do it, you can use any of the mocking frameworks available to request an object which implements the interface and then add implementations for the methods. This is a standard practice in TDD.
Also, you can simply use anonymous delegates to achieve most of your needs as per John Skeet's advice in the question your mention.
In Java, how do you get the original class object and/or class name of a Java EE (CDI) proxy?
When using getName() on a proxy instance, the name returned is something like
com.company.employeemgmt.EmployeeManager$Proxy$_$$_WeldSubclass
Is there some functionaliy in Java SE (7) or EE (6) that will return either the original, unproxied class instance or its name?
I need:
com.company.employeemgmt.EmployeeManager
Of course, I could simply use string manipulation, but I would like to know if such functionality is already Java-(EE)-inbuilt.
I already found java.reflect.Proxy, which I could use to detect proxies:
public static void doSomething( Class<? implements Serializable> managerClass )
{
if ( Proxy.isProxyClass( managerClass ) )
{
// unproxy how?
managerClass = managerClass.getUnproxiedClass();
}
// delegate
doSomething( managerClass.getName() );
}
public static void doSomething( String prefix )
{
// do real work
...
}
..., but how would you dereference the original class?
Update:
The trick would be to access MyUtil.doSomething( EmployeeManager.class ) (or MyUtil.doSomething( EmployeeManager.class.getName() )), but I would like to use/pass MyUtil.doSomething( this.getClass() ) (or MyUtil.doSomething( this.getClass().getName() )) from all clients as this code can be copied around without manual changes.
Since the proxy class inherits from the original class, I think that you can obtain the original class by getting the proxy superclass.
It depends. You can get the InvocationHandler for a proxy using Proxy.getInvocationHandler(manager). Alas, InvocationHandler is an interface with only one invoke method and with no feature that lets you get a target class; it all depends on the implementation.
As an example the CXF web servcie framework has a Client and uses a ClientProxy as an associated invocation handler, you can get the Client as such:
ClientProxy handler = (ClientProxy)Proxy.getInvocationHandler(proxiedObject);
Client client = handler.getClient();
To add insult to injury, it seems that the WeldInvocationHandler that you are probably using simply delegates the call to a org.jboss.wsf.spi.invocation.InvocationHandler that that it stores its delegate in a private field. So you need to do quite some magic with reflection to find out the actual class of the target object.
Since proxy implements interfaces it proxies, you can use Class<?>[] Class.getInterfaces()
to find out proxied class(es).
private Class<?> findProxiedClass(Object proxiedObject) {
Class<?> proxiedClass = proxiedObject.getClass();
if (proxiedObject instanceof Proxy) {
Class<?>[] ifaces = proxiedClass.getInterfaces();
if (ifaces.length == 1) {
proxiedClass = ifaces[0];
} else {
// We need some selection strategy here
// or return all of them
proxiedClass = ifaces[ifaces.length - 1];
}
}
return proxiedClass;
}
Test it with
#Test
public void testProxies() {
InvocationHandler handler = new InvocationHandler() {
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return null;
}
};
RandomAccess proxiedIface = (RandomAccess) Proxy.newProxyInstance(
RandomAccess.class.getClassLoader(),
new Class[] { RandomAccess.class },
handler);
Assert.assertEquals(RandomAccess.class, findProxiedClass(proxiedIface));
Assert.assertEquals(Object.class, findProxiedClass(new Object()));
}