Aditya Kumar
Aditya Kumar

Reputation: 297

Unable to call interface methods through proxy object

import java.lang.reflect.*;
import java.util.*;
public class proxy {
    public static void main(String[] args) {
        String s ="Happy";
        InvocationHandler handler = new Handler(s);
        Class[] interfaces = s.getClass().getInterfaces();
        Object myproxy = Proxy.newProxyInstance(null,interfaces,handler);
        System.out.println(myproxy.compareTo("hoppu"));
    }
}

class Handler implements InvocationHandler {
    public Handler(Object t) {
        target = t;
    }
    public Object invoke(Object proxy,Method m,Object[] args) throws Throwable {
        System.out.println(m.getName());
        return m.invoke(target,args);
    }
    private Object target;
}

Proxy object can call the interfaces as it implements them.I am getting this error when i am compiling this code.

proxy.java:19: cannot find symbol
symbol  : method compareTo(java.lang.String)
location: class java.lang.Object
    System.out.println(proxy.compareTo("hoppu"));
                            ^
1 error

I also tried with Integer ...same error.

Upvotes: 0

Views: 1609

Answers (3)

Caesar Ralf
Caesar Ralf

Reputation: 2233

You need to cast the returned proxy to String, because Object don't really have a compareTo(String).

EDIT

As I forgot, you will only be able to cast the created proxy to an interface. You could use @rgettman sollution.

Upvotes: 2

rgettman
rgettman

Reputation: 178293

You created your proxy object, but you didn't cast it to Comparable before calling compareTo. As an Object, the Java compiler doesn't know that proxy is anything but an Object.

The proxy returned must be cast to an interface that is supported by the object, not the actual class of the original object, according to the javadocs for Proxy.

Comparable c = (Comparable) Proxy.newProxyInstance(null,interfaces,handler);
System.out.println(c.compareTo("hoppu"));

Additionally, as pointed out by others, calling your class proxy and a variable proxy can be confusing. Conventionally, class names are capitalized, e.g. "Proxy", or even better, "MyProxy" here to avoid name collision with the built-in Java Proxy class.

Upvotes: 3

Eric Galluzzo
Eric Galluzzo

Reputation: 3241

Your proxy object has no compareTo method on it. Even if it does dynamically implement that interface from String, you cannot invoke that method without casting it to the appropriate interface (in this case, Comparable).

Upvotes: 0

Related Questions