Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java detect if class is a proxy

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.

like image 880
Johan Sjöberg Avatar asked Sep 21 '11 18:09

Johan Sjöberg


People also ask

How do you check if an object is a proxy?

So to determine if object is proxy, it's enough to initiate force object cloning. In can be done via postMessage function. If object is Proxy, it will failed to copy even it does not contain any functions.

What is a proxy class in Java?

A proxy class is a class created at runtime that implements a specified list of interfaces, known as proxy interfaces. A proxy instance is an instance of a proxy class. Each proxy instance has an associated invocation handler object, which implements the interface InvocationHandler .

What is the proxy class?

A proxy class allows you to hide the private data of a class from clients of the class. Providing clients of your class with a proxy class that knows only the public interface to your class enables the clients to use your class's services without giving the client access to your class's implementation details.

What is a proxy object in Java?

Proxy is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object.


1 Answers

Proxy.isProxyClass(Foo.class)

like image 61
jmj Avatar answered Sep 21 '22 13:09

jmj