私は、プライベートコンストラクタを持つクラスで失敗している単純な汎用の静的メソッドをJavaに持っています。ここに方法はあります:ここではジェネリックアサーションに失敗する
public static <E> void assertThatCtorIsPrivate(Class<E> clazz, Class<?>... parameters) throws NoSuchMethodException, InstantiationException, IllegalAccessException {
Preconditions.checkNotNull(clazz);
final Constructor<?> constructor = clazz.getConstructor(parameters);
constructor.setAccessible(true);
try {
constructor.newInstance((Object[]) null);
} catch(InvocationTargetException e) {
if(e.getCause() instanceof UnsupportedOperationException) {
throw new UnsupportedOperationException();
}
} finally {
constructor.setAccessible(false);
}
assert Modifier.isPrivate(constructor.getModifiers());
}
は、私がテストしようとしているクラスです:
私は単に持っている私のユニットテストでimport java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;
public final class DecodeJson {
private static final Gson GSON = new Gson();
private DecodeJson() {
throw new UnsupportedOperationException();
}
public static <E> E parse(final File file, Class<E> clazz) throws IOException {
Preconditions.checkNotNull(file);
Preconditions.checkArgument(file.exists() && file.canRead());
return GSON.fromJson(new FileReader(file), clazz);
}
public static <E> E parse(final String content, Class<E> clazz) throws IOException {
Preconditions.checkNotNull(content);
Preconditions.checkArgument(content.length() != 0);
return GSON.fromJson(content, clazz);
}
}
:
@Test(expected = UnsupportedOperationException.class)
public void testPrivateCtor() throws NoSuchMethodException, InstantiationException, IllegalAccessException {
ReflectionHelper.assertThatCtorIsPrivate(DecodeJson.class);
}
私はNoSuchMethodException
を取得しています私はfinal Constructor<?> constructor = clazz.getConstructor(parameters);
と呼ぶ。私はE
の代わりに?
を試しましたが、まだダイスはありません。どんな洞察?
ここで何を証明しようとしていますか?クラス自体を静的にすることはできませんか? –
@MarkChorley Javaのトップレベルクラスは静的ではありません。これは100%のコードカバレッジを見ることで、私は暖かく、あいまいな感じになります。 – djthoms