How can I check a class has no arguments constructor

≡放荡痞女 提交于 2020-01-02 01:12:21

问题


    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.

Is there another way?


回答1:


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

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

Rewritten with Stream.

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



回答2:


If you are using Spring you can use ClassUtils.hasConstructor():

ClassUtils.hasConstructor(obj.getClass());



回答3:


You can create a method that loops the class's constructor and check if any has no-arg constructor.

boolean hasNoArgConstructor(Class<?> klass) {
  for(Constructor c : klass.getDeclaredConstructors()) {
    if(c.getParameterTypes().length == 0) return true;
  }
  return false;
}

Note that by using getDeclaredConstructors(), default constructor added by the compiler will be included. Eg following will return true

class A { }

hasNoArgConstructor(A.class);

You can use getConstructors() but it will only check visible constructors. Hence following will return false

boolean hasNoArgConstructor(Class<?> klass) {
  for(Constructor c : klass.getConstructors()) {
    if(c.getParameterTypes().length == 0) return true;
  }
  return false;
}

class B {
  private B() {}
}

hasNoArgConstructor(B.class);


来源:https://stackoverflow.com/questions/27810634/how-can-i-check-a-class-has-no-arguments-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!