//不管有无默认的构造函数,直接生成类对象
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);
}
}
};
}
当不确定传输的类是否有无参的构造函数的时候。直接构建该类的对象。