001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.aop.cglib; 017 018import com.jfinal.aop.Interceptor; 019import com.jfinal.aop.InterceptorManager; 020import com.jfinal.aop.Invocation; 021import io.jboot.aop.InterceptorBuilderManager; 022import io.jboot.aop.InterceptorCache; 023import net.sf.cglib.proxy.MethodInterceptor; 024import net.sf.cglib.proxy.MethodProxy; 025 026import java.lang.reflect.Method; 027import java.util.HashSet; 028import java.util.Set; 029 030 031public class JbootCglibCallback implements MethodInterceptor { 032 033 private static final Set<String> excludedMethodName = buildExcludedMethodName(); 034 private static final InterceptorManager interManager = InterceptorManager.me(); 035 private static final InterceptorBuilderManager builderManager = InterceptorBuilderManager.me(); 036 037 @Override 038 public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { 039 if (excludedMethodName.contains(method.getName())) { 040 return methodProxy.invokeSuper(target, args); 041 } 042 043 Class<?> targetClass = target.getClass().getSuperclass(); 044 //ClassUtil.getUsefulClass(target.getClass()); 045 046 InterceptorCache.MethodKey key = InterceptorCache.getMethodKey(targetClass, method); 047 Interceptor[] inters = InterceptorCache.get(key); 048 if (inters == null) { 049 inters = interManager.buildServiceMethodInterceptor(targetClass, method); 050 inters = builderManager.build(targetClass, method, inters); 051 052 InterceptorCache.put(key, inters); 053 } 054 055 if (inters.length == 0) { 056 return methodProxy.invokeSuper(target, args); 057 } else { 058 Invocation invocation = new Invocation(target, method, inters, 059 x -> methodProxy.invokeSuper(target, x), args); 060 invocation.invoke(); 061 return invocation.getReturnValue(); 062 } 063 } 064 065 066 private static Set<String> buildExcludedMethodName() { 067 Set<String> excludedMethodName = new HashSet<String>(64, 0.25F); 068 Method[] methods = Object.class.getDeclaredMethods(); 069 for (Method m : methods) { 070 excludedMethodName.add(m.getName()); 071 } 072 // getClass() registerNatives() can not be enhanced 073 // excludedMethodName.remove("getClass"); 074 // excludedMethodName.remove("registerNatives"); 075 return excludedMethodName; 076 } 077 078} 079 080