Fliegend的乱七八糟空间

新手入门,Hello World!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

开发过程中遇到一个不能直接调用泛型工具类的方法,因此需要通过反射来摆脱直接依赖。

被调用静态方法示例

public class test{
    public static <T> T get(Class<T> tClass){
        try {
            return test2.getData(tClass);
        } catch (Exception e){
            return null;
        }
    }
}

 

调用者示例

1     public static <T> T getData(Class<T> tClass) {
2         try {
3             MethodType methodType = MethodType.methodType(Object.class, Class.class);
4             MethodHandle method = MethodHandles.lookup().findStatic(Class.forName("com.xxx.adapter.context.test"), "get", methodType);
5             return (T) method.invoke(tClass);
6         }catch (Throwable e){
7             return null;
8         }
9     }

 

一开始没搞明白如何能获取到泛型方法的方法句柄。

后来发现可以直接用 MethodType.methodType(Object.class, Class.class) 表示。。。。基础知识还是重要。

 

posted on 2021-12-13 16:11  Fliegend  阅读(417)  评论(0编辑  收藏  举报