Andrei I Andrei I - 6 months ago 211
Java Question

What is com.sun.proxy.$Proxy

I have seen that when errors occur deep in different frameworks (e.g frameworks implementing the EJB specification or some JPA providers) the stacktrace contain classes like

com.sun.proxy.$Proxy
. I know what a Proxy is, but I am looking for a more technical and more java specific answer.


  1. What are they?

  2. How are they created?

  3. What is there relationship to the JVM? Are they JVM implementation specific?


Answer
  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

Comments