Fix two ErrorProne warnings in TypeUtils

1) Prefer .getConstructor().newInstance() over .newInstance()
   because otherwise checked exceptions can be propagated from
   the constructor even though they aren't declared.
2) Use the type T in the parameters to instantiate().

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=138874730
This commit is contained in:
cgoldfeder 2016-11-11 07:35:06 -08:00 committed by Ben McIlwain
parent f742ac8056
commit d5104df453
2 changed files with 7 additions and 5 deletions

View file

@ -103,7 +103,10 @@ public abstract class ForeignKeyIndex<E extends EppResource> extends BackupGroup
*/ */
public static <E extends EppResource> ForeignKeyIndex<E> create( public static <E extends EppResource> ForeignKeyIndex<E> create(
E resource, DateTime deletionTime) { E resource, DateTime deletionTime) {
ForeignKeyIndex<E> instance = instantiate(RESOURCE_CLASS_TO_FKI_CLASS.get(resource.getClass())); @SuppressWarnings("unchecked")
Class<? extends ForeignKeyIndex<E>> fkiClass =
(Class<? extends ForeignKeyIndex<E>>) RESOURCE_CLASS_TO_FKI_CLASS.get(resource.getClass());
ForeignKeyIndex<E> instance = instantiate(fkiClass);
instance.topReference = Key.create(resource); instance.topReference = Key.create(resource);
instance.foreignKey = resource.getForeignKey(); instance.foreignKey = resource.getForeignKey();
instance.deletionTime = deletionTime; instance.deletionTime = deletionTime;

View file

@ -46,13 +46,12 @@ public class TypeUtils {
} }
} }
@SuppressWarnings("unchecked") public static <T> T instantiate(Class<? extends T> clazz) {
public static <T> T instantiate(Class<?> clazz) {
checkArgument(Modifier.isPublic(clazz.getModifiers()), checkArgument(Modifier.isPublic(clazz.getModifiers()),
"AppEngine's custom security manager won't let us reflectively access non-public types"); "AppEngine's custom security manager won't let us reflectively access non-public types");
try { try {
return (T) clazz.newInstance(); return clazz.getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException e) { } catch (ReflectiveOperationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }