如何检查类没有参数构造函数

如何检查类没有参数构造函数

问题描述:

    Object obj = new Object();
    try {
        obj.getClass().getConstructor();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        dosomething();          
        e.printStackTrace();
    }

我不想这样检查,因为它会抛出异常。

I don't want check like this, because it throw a Exception.

还有其他办法吗?

你可以得到所有构造函数 s并检查它们的参数数量,当你找到一个参数时停止。

You can get all Constructors and check their number of parameters, stopping when you find one that has 0.

private boolean hasParameterlessPublicConstructor(Class<?> clazz) {
    for (Constructor<?> constructor : clazz.getConstructors()) {
        // In Java 7-, use getParameterTypes and check the length of the array returned
        if (constructor.getParameterCount() == 0) { 
            return true;
        }
    }
    return false;
}

你必须使用 getDeclaredConstructors()非公共构造函数。

You'd have to use getDeclaredConstructors() for non-public constructors.

Stream 重写。

private boolean hasParameterlessConstructor(Class<?> clazz) {
    return Stream.of(clazz.getConstructors())
                 .anyMatch((c) -> c.getParameterCount() == 0);
}