Ich habe eine einfache generische, statische Methode in Java, die für eine Klasse fehlschlägt, die einen privaten Konstruktor hat. Hier ist die Methode:Generische Assertion fehlgeschlagen
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());
}
Hier wird die Klasse I Test bin versucht:
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);
}
}
In meinem Unit-Test ich einfach haben:
@Test(expected = UnsupportedOperationException.class)
public void testPrivateCtor() throws NoSuchMethodException, InstantiationException, IllegalAccessException {
ReflectionHelper.assertThatCtorIsPrivate(DecodeJson.class);
}
Ich erhalte ein NoSuchMethodException
wenn ich final Constructor<?> constructor = clazz.getConstructor(parameters);
anrufe. Ich habe versucht, ?
für E
und immer noch keine Würfel zu ersetzen. Irgendeine Einsicht?
Was möchten Sie hier beweisen? Könnten Sie nicht einfach die Klasse selbst statisch machen? –
@MarkChorley Klassen der obersten Ebene in Java können nicht statisch sein. Dies ist zu sehen, dass 100% Code-Abdeckung, so dass ich das warme, flauschige Gefühl. – djthoms