简体   繁体   中英

How can I check a class has no arguments constructor

    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?

You can get all Constructor s 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);
}

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

ClassUtils.hasConstructor(obj.getClass());

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM