Is it possible to detect if a class is a proxy (dynamic, cglib or otherwise)?
Let classes A
and B
implement a common interface I
. Then I need to define a routine classEquals
of signature
public boolean classEquals(Class<? extends I> a, Class<? extends I> b);
such that it evaluates to true only if a.equals(b)
or Proxy(a).equals(b)
, where Proxy(a)
denotes a dynamic proxy of type A
(dynamic, cglib or otherwise).
With the assistance of @Jigar Joshi
, this is what it looks like so far:
public boolean classEquals(Class a, Class b) {
if (Proxy.isProxyClass(a)) {
return classEquals(a.getSuperclass(), b);
}
return a.equals(b);
}
The problem is that it doesn't detect e.g., a CGLIB proxy.
Proxy.isProxyClass(Foo.class)
If instanceof
is acceptable, then clazz.isInstance(b)
should work as well.
Edit:
I wrote that before reading your modified answer. There is a similar method for classes as well:
b.isAssignableFrom(a)
no, in general you can't tell if an object is a proxy. and that's simply because it's hard to define what is a proxy. you can implement an interface and use it as a proxy, you can use cglib, asm, javassist, plastic, jdk or generate bytecode on the fly by yourself. it is no different than loading xxx.class file.
what you are thinking about is probably checking if the object is created by cglib, asm or other specific library. in such case - usually yes. most libraries have their own fingerprint that can be discovered. but in general it's not possible