com.github.dreamroute.locker.util.PluginUtil Maven / Gradle / Ivy
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.dreamroute.locker.util;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.util.ObjectUtils;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author w.dehai
*/
public final class PluginUtil {
private PluginUtil() {} // private constructor
/**
*
* Recursive get the original target object.
*
* If integrate more than a plugin, maybe there are conflict in these plugins,
* because plugin will proxy the object.
* So, here get the orignal target object
*
* @param target proxy-object
* @return original target object
*/
public static Object processTarget(Object target) {
if (Proxy.isProxyClass(target.getClass())) {
MetaObject mo = SystemMetaObject.forObject(target);
return processTarget(mo.getValue("h.target"));
}
return target;
}
/**
* 获取cls所有方法,包括父接口的方法
*/
public static Method[] getAllMethods(Class> cls) {
Set> all = getAllParentInterface(cls);
all.add(cls);
return all.stream().flatMap(c -> Arrays.stream(c.getDeclaredMethods())).toArray(Method[]::new);
}
public static Set> getAllParentInterface(Class> cls) {
Set> result = new HashSet<>();
recursiveCls(cls, result);
return result;
}
private static void recursiveCls(Class> cls, Set> result) {
Class>[] interfaces = cls.getInterfaces();
if (!ObjectUtils.isEmpty(interfaces)) {
result.addAll(Arrays.asList(interfaces));
Arrays.stream(interfaces).forEach(inter -> recursiveCls(inter, result));
}
}
}