How do I get the underlying type of a proxy object in java?

前端 未结 7 1117
旧时难觅i
旧时难觅i 2020-12-09 02:05

I\'d like to access the classname of the underlying class which is an instance of java.lang.reflect.Proxy.

Is this possible?

相关标签:
7条回答
  • 2020-12-09 03:00

    Well a Proxy instance won't be an instance of java.lang.reflect.Proxy per se. Rather, it will be an instance of a subclass of java.lang.reflect.Proxy.

    Anyway, the way to get the actual proxy classes name is:

    Proxy proxy = ...
    System.err.println("Proxy class name is " + proxy.getClass().getCanonicalName());
    

    However, you cannot get the name of the class that the Proxy is a proxy for, because:

    1. you proxy interfaces not classes, and
    2. a Proxy can be a proxy for multiple interfaces

    However, from looking at the source code of the ProxyGenerator class, it seems that the interfaces are recorded in the generated proxy class as the interfaces of the class. So you should be able to get them at runtime via the proxy classes Class object; e.g.

    Class<?>[] classes = proxy.getClass().getInterfaces();
    

    (Note: I've not tried this ...)

    0 讨论(0)
提交回复
热议问题