I have trying to make a simple dynamic proxy example work without success. I assume I am doing something wrong but reading some java modules tuts and proxy tuts did not help me understand... the code is super basic with an interface, its implementation, an invocatgion handler and the class with the main method that runs the example:
package com.example.proxy;
public interface Foo {
public String foo(String s);
}
package com.example.proxy;
public class FooImpl implements Foo{
@Override
public String foo(String str) {
return str;
}
}
package com.example.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class FooProxy implements InvocationHandler{
Foo foo;
public FooProxy(Foo s){
this.foo = s;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("%#$%#5^$@5^$@5^ PROXY");
return ("[proxied] "+method.invoke(this.foo, args));
}
}
package com.example.proxy;
import java.lang.reflect.Proxy;
public class MainTest {
public static void main(String [] args){
Foo o = (Foo)Proxy.newProxyInstance(Foo.class.getClassLoader(), Foo.class.getInterfaces(), new FooProxy(new FooImpl() ));
}
}
running maintest yeilds:
Exception in thread "main" java.lang.ClassCastException: class jdk.proxy1.$Proxy0 cannot be cast to class com.example.proxy.Foo (jdk.proxy1.$Proxy0 is in module jdk.proxy1 of loader 'app'; com.example.proxy.Foo is in unnamed module of loader 'app')
at com.example.proxy.MainTest.main(MainTest.java:10)
I tried exposing com.example.proxy in module-info.java explicitly, trying some opens etc but nothing helped so I assume I do not get something. can anyone help point me in the right direction thanks!
As suggested by Sweeper, we should use new Class<?>[] { Foo.class }
instead of Foo.class.getInterfaces()
From Class#getInterfaces:
If this Class object represents a class or interface that implements no interfaces, the method returns an array of length 0.
Hence Foo.class.getInterfaces()
is actually returning an empty array.