How can I check a class has no arguments construct

2019-04-20 15:37发布

    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?

3条回答
地球回转人心会变
2楼-- · 2019-04-20 16:05

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);
}
查看更多
疯言疯语
3楼-- · 2019-04-20 16:12

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);
查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-20 16:25

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

ClassUtils.hasConstructor(obj.getClass());
查看更多
登录 后发表回答