我怎样才能检查一个类没有参数构造函数

Q.y*_*uan 12 java reflection

    Object obj = new Object();
    try {
        obj.getClass().getConstructor();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        dosomething();          
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

我不想像这样检查,因为它抛出异常.

还有另外一种方法吗?

Sot*_*lis 14

您可以获取所有Constructors并检查其参数数量,当您找到具有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;
}
Run Code Online (Sandbox Code Playgroud)

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

改写Stream.

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

  • 构造函数类没有getParameterCount()方法:http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Constructor.html (2认同)

pru*_*nge 5

如果您使用的是Spring,则可以使用ClassUtils.hasConstructor()

ClassUtils.hasConstructor(obj.getClass());
Run Code Online (Sandbox Code Playgroud)