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

前端 未结 7 1123
旧时难觅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:59

    Here was the solution we used with my team (we need the name of the class behind the proxy) :

    if (getTargetName(yourBean) ... ) {
    
    }
    

    With this little helper :

    private String getTargetName(final Object target) {
    
        if (target == null) {
            return "";
        }
    
        if (targetClassIsProxied(target)) {
    
            Advised advised = (Advised) target;
    
            try {
    
                return advised.getTargetSource().getTarget().getClass().getCanonicalName();
            } catch (Exception e) {
    
                return "";
            }
        }
    
        return target.getClass().getCanonicalName();
    }
    
    private boolean targetClassIsProxied(final Object target) {
    
        return target.getClass().getCanonicalName().contains("$Proxy");
    }
    

    Hope it helps!

提交回复
热议问题