Java 泛型断言失败

Java 泛型断言失败,java,unit-testing,generics,reflection,code-coverage,Java,Unit Testing,Generics,Reflection,Code Coverage,我在Java中有一个简单的通用静态方法,对于一个具有私有构造函数的类来说是失败的。方法如下: public static <E> void assertThatCtorIsPrivate(Class<E> clazz, Class<?>... parameters) throws NoSuchMethodException, InstantiationException, IllegalAccessException { Preconditions.c

我在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());
}

当我调用
final Constructor=clazz.getConstructor(参数)时,我得到一个
NoSuchMethodException
。我试着用
代替
E
,但还是没有骰子。任何洞察?

执行
Class.getConstructor(Class…parameterTypes)
将只返回可访问的构造函数

private
构造函数肯定无法从外部访问


要获取不可访问的构造函数,请使用
Class.getDeclaredConstructor(Class…parameterTypes)
执行
Class.getConstructor(Class…parameterTypes)
将只返回可访问的构造函数

private
构造函数肯定无法从外部访问


要获取不可访问的构造函数,请使用
Class.getDeclaredConstructor(Class…parameterTypes)

您在这里试图证明什么?你能不能让类本身成为静态的?@MarkChorley Java中的顶级类不能是静态的。这是为了看到100%的代码覆盖率,所以我有一种温暖、模糊的感觉。你想证明什么?你能不能让类本身成为静态的?@MarkChorley Java中的顶级类不能是静态的。这是为了看到100%的代码覆盖率,所以我得到了温暖,模糊的感觉。啊。。。我想这是一个关注细节的关键时刻。谢谢啊。。。我想这是一个关注细节的关键时刻。谢谢
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);
}