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.
- What are they?
- How are they created?
- What is there relationship to the JVM? Are they JVM implementation specific?
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.You create them by using the call
The arguments are:
classLoader
. Once the class is generated, it is loaded with this class loader.interfaces
. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.invocationHandler
. This is how your proxy knows what to do when a method is invoked. It is an object that implementsInvocationHandler
. When a method from any of the supported interfaces, orhashCode
,equals
, ortoString
, is invoked, the methodinvoke
is invoked on the handler, passing theMethod
object for the method to be invoked and the arguments passed.For more on this, see the documentation for the
Proxy
class.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.
What are they?
Nothing special. Just as same as common Java Class Instance.
But those class are
Synthetic proxy classes
created byjava.lang.reflect.Proxy#newProxyInstance
What is there relationship to the JVM? Are they JVM implementation specific?
Introduced in 1.3
http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection
It is a part of Java. so each JVM should support it.
How are they created (Openjdk7 source)?
In short : they are created using JVM ASM tech ( defining javabyte code at runtime )
something using same tech:
What happens after calling
java.lang.reflect.Proxy#newProxyInstance
getProxyClass0
to obtain a `Class`
ProxyGenerator.generateProxyClass
which return a byte[]define class
to load the generated$Proxy
Class (the classname you have seen)What happens in magic sun.misc.ProxyGenerator
each method is build with same bytecode like
invocation handler
'sinvoke()
invocation handler
'sinvoke()
the class(bytecode) represent in form of
byte[]
How to draw a class
Thinking your java codes are compiled into bytecodes, just do this at runtime
Talk is cheap show you the code
core method in sun/misc/ProxyGenerator.java
generateClassFile
addProxyMethod
Full code about gen the proxy method