001package ball.lang.reflect; 002/*- 003 * ########################################################################## 004 * Utilities 005 * $Id: InterceptingInvocationHandler.java 7215 2021-01-03 18:39:51Z ball $ 006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-util/trunk/src/main/java/ball/lang/reflect/InterceptingInvocationHandler.java $ 007 * %% 008 * Copyright (C) 2008 - 2021 Allen D. Ball 009 * %% 010 * Licensed under the Apache License, Version 2.0 (the "License"); 011 * you may not use this file except in compliance with the License. 012 * You may obtain a copy of the License at 013 * 014 * http://www.apache.org/licenses/LICENSE-2.0 015 * 016 * Unless required by applicable law or agreed to in writing, software 017 * distributed under the License is distributed on an "AS IS" BASIS, 018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 019 * See the License for the specific language governing permissions and 020 * limitations under the License. 021 * ########################################################################## 022 */ 023import java.lang.reflect.Method; 024import lombok.Getter; 025import lombok.RequiredArgsConstructor; 026import lombok.ToString; 027 028import static org.apache.commons.lang3.reflect.MethodUtils.invokeMethod; 029 030/** 031 * "Intercepting" {@link java.lang.reflect.InvocationHandler} 032 * implementation. 033 * 034 * @param <T> The type of the "wrapped" target. 035 * 036 * {@bean.info} 037 * 038 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball} 039 * @version $Revision: 7215 $ 040 */ 041@RequiredArgsConstructor @ToString 042public class InterceptingInvocationHandler<T> extends DefaultInvocationHandler { 043 @Getter private final T target; 044 045 /** 046 * Subclasses may declare methods with the same signature of a proxied 047 * interface method which will be invoked (as a sort of listener) before 048 * invoking the target method. If the invoked {@link Method}'s 049 * declaring class is assignable from the target's class, the 050 * {@link Method} is invoked on the target. 051 * 052 * @param proxy The proxy instance. 053 * @param method The {@link Method}. 054 * @param argv The argument array. 055 * 056 * @return The value to return from the {@link Method} invocation. 057 * 058 * @throws Exception If the {@link Method} cannot be invoked. 059 */ 060 @Override 061 public Object invoke(Object proxy, Method method, Object[] argv) throws Throwable { 062 try { 063 invokeMethod(this, true, 064 method.getName(), 065 argv, method.getParameterTypes()); 066 } catch (Exception exception) { 067 } 068 069 Object result = null; 070 071 if (method.isDefault()) { 072 result = super.invoke(proxy, method, argv); 073 } else if (method.getDeclaringClass().isAssignableFrom(target.getClass())) { 074 result = method.invoke(target, argv); 075 } else { 076 result = super.invoke(proxy, method, argv); 077 } 078 079 return result; 080 } 081}