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

前端 未结 7 1126
旧时难觅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 02:43

    First of all, java.lang.reflect.Proxy works only on interfaces. The framework creates a descendant class that implements the interface(s) but extends java.lang.reflect.Proxy rather than an application class that may be of interest to you. There is no inheritance of multiple classes in modern (2016) Java.

    In my case, the debugger shows that the object of interest is in the obj field in the invocation handler of the proxy object.

        Object handler = Proxy.getInvocationHandler(somethingProxied);
        Class handlerClass = handler.getClass();
        Field objField = handlerClass.getDeclaredField("obj");
        objField.setAccessible(true);
        Object behindProxy = objField.get(handler);
    

    You will have to catch() two exceptions: NoSuchFieldException and IllegalAccessException.

    I found it useful to print the list of fields of declared fields from the catch() clause:

    ...
    } catch (NoSuchFieldException nsfe) {
        nsfe.printStackTrace();
    
        Object handler = Proxy.getInvocationHandler(somethingProxied);
        Class handlerClass = handler.getClass();
        for (Field f : handlerClass.getDeclaredFields()) {
            f.setAccessible(true);
            String classAndValue = null;
            try {
                Object v = f.get(handler);
                classAndValue= "" + (v == null ? "" : v.getClass()) + " : " + v;
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
            }
            System.out.println(" field: " + f.getName() + " = " + classAndValue+ ";");
        }
    ...
    }
    

    Note that different frameworks use different proxies and even different techniques of proxying. The solution that worked for me may be not applicable in your case. (It definitely will not work for Javassist or Hibernate proxies.)

提交回复
热议问题