java.lang.Class.getConstructors()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(10.4k)|赞(0)|评价(0)|浏览(269)

本文整理了Java中java.lang.Class.getConstructors()方法的一些代码示例,展示了Class.getConstructors()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Class.getConstructors()方法的具体详情如下:
包路径:java.lang.Class
类名称:Class
方法名:getConstructors

Class.getConstructors介绍

[英]Returns an array containing Constructor objects for all public constructors for this Class. If there are no public constructors or if this Class represents an array class, a primitive type or void then an empty array is returned.
[中]返回包含此类所有公共构造函数的构造函数对象的数组。如果没有公共构造函数,或者该类表示数组类、基元类型或void,则返回空数组。

代码示例

代码示例来源:origin: spring-projects/spring-framework

private static Constructor<?> getEndpointConstructor() {
  for (Constructor<?> current : TyrusEndpointWrapper.class.getConstructors()) {
    Class<?>[] types = current.getParameterTypes();
    if (Endpoint.class == types[0] && EndpointConfig.class == types[1]) {
      return current;
    }
  }
  throw new IllegalStateException("No compatible Tyrus version found");
}

代码示例来源:origin: apache/incubator-dubbo

public MapDeserializer(Class type) {
  if (type == null)
    type = HashMap.class;
  _type = type;
  Constructor[] ctors = type.getConstructors();
  for (int i = 0; i < ctors.length; i++) {
    if (ctors[i].getParameterTypes().length == 0)
      _ctor = ctors[i];
  }
  if (_ctor == null) {
    try {
      _ctor = HashMap.class.getConstructor(new Class[0]);
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }
}

代码示例来源:origin: prestodb/presto

public static Optional<Constructor<?>> findConstructor(Class<?> clazz)
{
  Constructor<?>[] constructors = clazz.getConstructors();
  checkArgument(constructors.length <= 1, "Class [%s] must have no more than 1 public constructor");
  if (constructors.length == 0) {
    return Optional.empty();
  }
  return Optional.of(constructors[0]);
}

代码示例来源:origin: junit-team/junit4

private ParameterSupplier buildParameterSupplierFromClass(
    Class<? extends ParameterSupplier> cls) throws Exception {
  Constructor<?>[] supplierConstructors = cls.getConstructors();
  for (Constructor<?> constructor : supplierConstructors) {
    Class<?>[] parameterTypes = constructor.getParameterTypes();
    if (parameterTypes.length == 1
        && parameterTypes[0].equals(TestClass.class)) {
      return (ParameterSupplier) constructor.newInstance(clazz);
    }
  }
  return cls.newInstance();
}

代码示例来源:origin: apache/incubator-dubbo

public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException {
  Constructor<?> targetConstructor;
  try {
    targetConstructor = clazz.getConstructor(new Class<?>[]{paramType});
  } catch (NoSuchMethodException e) {
    targetConstructor = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
      if (Modifier.isPublic(constructor.getModifiers())
          && constructor.getParameterTypes().length == 1
          && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) {
        targetConstructor = constructor;
        break;
      }
    }
    if (targetConstructor == null) {
      throw e;
    }
  }
  return targetConstructor;
}

代码示例来源:origin: libgdx/libgdx

/** Returns an array of {@link Constructor} containing the public constructors of the class represented by the supplied Class. */
static public Constructor[] getConstructors (Class c) {
  java.lang.reflect.Constructor[] constructors = c.getConstructors();
  Constructor[] result = new Constructor[constructors.length];
  for (int i = 0, j = constructors.length; i < j; i++) {
    result[i] = new Constructor(constructors[i]);
  }
  return result;
}

代码示例来源:origin: libgdx/libgdx

/** Returns an array of {@link Constructor} containing the public constructors of the class represented by the supplied Class. */
static public Constructor[] getConstructors (Class c) {
  java.lang.reflect.Constructor[] constructors = c.getConstructors();
  Constructor[] result = new Constructor[constructors.length];
  for (int i = 0, j = constructors.length; i < j; i++) {
    result[i] = new Constructor(constructors[i]);
  }
  return result;
}

代码示例来源:origin: apache/incubator-dubbo

public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException {
  Constructor<?> targetConstructor;
  try {
    targetConstructor = clazz.getConstructor(new Class<?>[]{paramType});
  } catch (NoSuchMethodException e) {
    targetConstructor = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
      if (Modifier.isPublic(constructor.getModifiers())
          && constructor.getParameterTypes().length == 1
          && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) {
        targetConstructor = constructor;
        break;
      }
    }
    if (targetConstructor == null) {
      throw e;
    }
  }
  return targetConstructor;
}

代码示例来源:origin: junit-team/junit4

private void validateParameterSupplier(Class<? extends ParameterSupplier> supplierClass, List<Throwable> errors) {
  Constructor<?>[] constructors = supplierClass.getConstructors();
  
  if (constructors.length != 1) {
    errors.add(new Error("ParameterSupplier " + supplierClass.getName() + 
               " must have only one constructor (either empty or taking only a TestClass)"));
  } else {
    Class<?>[] paramTypes = constructors[0].getParameterTypes();
    if (!(paramTypes.length == 0) && !paramTypes[0].equals(TestClass.class)) {
      errors.add(new Error("ParameterSupplier " + supplierClass.getName() + 
                 " constructor must take either nothing or a single TestClass instance"));
    }
  }
}

代码示例来源:origin: redisson/redisson

private void readObject(ObjectInputStream in)
  throws IOException, ClassNotFoundException
{
  javaClass = getClassObject(in.readUTF());
  constructors = javaClass.getConstructors();
  methods = null;
}

代码示例来源:origin: junit-team/junit4

/**
 * Returns the only public constructor in the class, or throws an {@code
 * AssertionError} if there are more or less than one.
 */
public Constructor<?> getOnlyConstructor() {
  Constructor<?>[] constructors = clazz.getConstructors();
  Assert.assertEquals(1, constructors.length);
  return constructors[0];
}

代码示例来源:origin: greenrobot/EventBus

public TestRunner(Context context, TestParams testParams, EventBus controlBus) {
  this.controlBus = controlBus;
  tests = new ArrayList<Test>();
  for (Class<? extends Test> testClazz : testParams.getTestClasses()) {
    try {
      Constructor<?>[] constructors = testClazz.getConstructors();
      Constructor<? extends Test> constructor = testClazz.getConstructor(Context.class, TestParams.class);
      Test test = constructor.newInstance(context, testParams);
      tests.add(test);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

代码示例来源:origin: google/j2objc

/**
 * Returns the only public constructor in the class, or throws an {@code
 * AssertionError} if there are more or less than one.
 */
public Constructor<?> getOnlyConstructor() {
  Constructor<?>[] constructors = fClass.getConstructors();
  Assert.assertEquals(1, constructors.length);
  return constructors[0];
}

代码示例来源:origin: google/j2objc

public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual)  {
    try {
      Class<?> clazz = Class.forName("org.mockito.exceptions.verification.junit.ArgumentsAreDifferent");
      AssertionError throwable = (AssertionError) clazz.getConstructors()[0].newInstance(message, wanted, actual);
      return throwable;
    } catch (Throwable t) {
//            throw the default exception in case of problems
      return new ArgumentsAreDifferent(message);
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public Constructor<?>[] getPreferredConstructors() {
  Class<?> clazz = getBeanClass();
  Constructor<?> primaryCtor = BeanUtils.findPrimaryConstructor(clazz);
  if (primaryCtor != null) {
    return new Constructor<?>[] {primaryCtor};
  }
  Constructor<?>[] publicCtors = clazz.getConstructors();
  if (publicCtors.length > 0) {
    return publicCtors;
  }
  return null;
}

代码示例来源:origin: spring-projects/spring-framework

private Mono<?> createAttribute(
    String attributeName, Class<?> clazz, BindingContext context, ServerWebExchange exchange) {
  Constructor<?> ctor = BeanUtils.findPrimaryConstructor(clazz);
  if (ctor == null) {
    Constructor<?>[] ctors = clazz.getConstructors();
    if (ctors.length == 1) {
      ctor = ctors[0];
    }
    else {
      try {
        ctor = clazz.getDeclaredConstructor();
      }
      catch (NoSuchMethodException ex) {
        throw new IllegalStateException("No primary or default constructor found for " + clazz, ex);
      }
    }
  }
  return constructAttribute(ctor, attributeName, context, exchange);
}

代码示例来源:origin: google/guava

private static <X extends Exception> X newWithCause(Class<X> exceptionClass, Throwable cause) {
 // getConstructors() guarantees this as long as we don't modify the array.
 @SuppressWarnings({"unchecked", "rawtypes"})
 List<Constructor<X>> constructors = (List) Arrays.asList(exceptionClass.getConstructors());
 for (Constructor<X> constructor : preferringStrings(constructors)) {
  @Nullable X instance = newFromConstructor(constructor, cause);
  if (instance != null) {
   if (instance.getCause() == null) {
    instance.initCause(cause);
   }
   return instance;
  }
 }
 throw new IllegalArgumentException(
   "No appropriate constructor for exception of type "
     + exceptionClass
     + " in response to chained exception",
   cause);
}

代码示例来源:origin: weibocom/motan

private void checkConstructorPublic(Class<T> clz) {
  Constructor<?>[] constructors = clz.getConstructors();
  if (constructors == null || constructors.length == 0) {
    failThrows(clz, "Error has no public no-args constructor");
  }
  for (Constructor<?> constructor : constructors) {
    if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) {
      return;
    }
  }
  failThrows(clz, "Error has no public no-args constructor");
}

代码示例来源:origin: apache/incubator-dubbo

public BeanDeserializer(Class cl) {
  _type = cl;
  _methodMap = getMethodMap(cl);
  _readResolve = getReadResolve(cl);
  Constructor[] constructors = cl.getConstructors();
  int bestLength = Integer.MAX_VALUE;
  for (int i = 0; i < constructors.length; i++) {
    if (constructors[i].getParameterTypes().length < bestLength) {
      _constructor = constructors[i];
      bestLength = _constructor.getParameterTypes().length;
    }
  }
  if (_constructor != null) {
    _constructor.setAccessible(true);
    Class[] params = _constructor.getParameterTypes();
    _constructorArgs = new Object[params.length];
    for (int i = 0; i < params.length; i++) {
      _constructorArgs[i] = getParamArg(params[i]);
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Return the resolved autowire code,
 * (resolving AUTOWIRE_AUTODETECT to AUTOWIRE_CONSTRUCTOR or AUTOWIRE_BY_TYPE).
 * @see #AUTOWIRE_AUTODETECT
 * @see #AUTOWIRE_CONSTRUCTOR
 * @see #AUTOWIRE_BY_TYPE
 */
public int getResolvedAutowireMode() {
  if (this.autowireMode == AUTOWIRE_AUTODETECT) {
    // Work out whether to apply setter autowiring or constructor autowiring.
    // If it has a no-arg constructor it's deemed to be setter autowiring,
    // otherwise we'll try constructor autowiring.
    Constructor<?>[] constructors = getBeanClass().getConstructors();
    for (Constructor<?> constructor : constructors) {
      if (constructor.getParameterCount() == 0) {
        return AUTOWIRE_BY_TYPE;
      }
    }
    return AUTOWIRE_CONSTRUCTOR;
  }
  else {
    return this.autowireMode;
  }
}

相关文章

Class类方法