0
点赞
收藏
分享

微信扫一扫

UnsafeAllocator不安全类,java直接创建对象

龙驹书房 2022-02-16 阅读 79
  //不管有无默认的构造函数,直接生成类对象
    private static <T> ObjectConstructor<T> newUnsafeAllocator(
            final Class<? super T> rawType) {
        return new ObjectConstructor<T>() {
            private final UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
            @SuppressWarnings("unchecked")
            @Override public T construct() {
                try {
                    Object newInstance = unsafeAllocator.newInstance(rawType);
                    return (T) newInstance;
                } catch (Exception e) {
                    throw new RuntimeException(("Unable to invoke no-args constructor  "
                            + "Register an InstanceCreator with Gson for this type may fix this problem."), e);
                }
            }
        };
    }

当不确定传输的类是否有无参的构造函数的时候。直接构建该类的对象。

举报

相关推荐

0 条评论