Java detect if class is a proxy

2019-04-21 00:31发布

问题:

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.

回答1:

Proxy.isProxyClass(Foo.class)



回答2:

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)



回答3:

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