Java detect if class is a proxy
Asked Answered
R

3

17

Is it possible to detect if a class is a proxy (dynamic, cglib or otherwise)?

Let classes Aand 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.

Riddle answered 21/9, 2011 at 18:7 Comment(6)
In your test method, I suppose Proxy(A.class) returns a proxy object for A. What should be the result of test(new A(), A.class)?Salinasalinas
@Arian, it should evaluate to trueJanitor
So you don't want to detect proxies, but you want to find instances of a class, even if they are generated by an unknown mocking/proxy framework? What about instanceof?Salinasalinas
@Arian, good comment. Although I'm working with Classes and not Objects, which unfortunately doesn't let me use instanceofJanitor
CGLIB provides a Proxy.isProxyClass in its own packages. That might detect them.Preparation
"true only if a.equals(b) and Proxy(a).equals(b)" did you mean 'or'?Salinasalinas
A
20

Proxy.isProxyClass(Foo.class)

Adolfoadolph answered 21/9, 2011 at 18:10 Comment(3)
Awesome in that it detects a DynamicProxy, yet doesn't seem to recognize Mockito created CGLIB proxies .Janitor
do Foo.getClass().getName()Adolfoadolph
In case of CGLIB proxy use Enhancer.isEnhanced(class)Octavia
W
2

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

Whereof answered 24/5, 2013 at 18:11 Comment(0)
S
1

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)

Salinasalinas answered 21/9, 2011 at 18:54 Comment(1)
Interesting, but doesn't seem to apply nicely to class-to-class comparisons.Janitor

© 2022 - 2024 — McMap. All rights reserved.