如何检查类没有参数构造函数 [英] How can I check a class has no arguments constructor

查看:307
本文介绍了如何检查类没有参数构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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);
}

这篇关于如何检查类没有参数构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆