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

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

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

Class.getDeclaredConstructor介绍

[英]Returns a Constructor object which represents the constructor matching the given parameter types that is declared by the class represented by this Class. (Class[]) null is equivalent to the empty array.

Use #getConstructor if you want to search superclasses.
[中]返回一个构造函数对象,该对象表示与该类所表示的类声明的给定参数类型相匹配的构造函数。(类[])null相当于空数组。
如果要搜索超类,请使用#getConstructor。

代码示例

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

public static boolean checkZeroArgConstructor(Class clazz) {
  try {
    clazz.getDeclaredConstructor();
    return true;
  } catch (NoSuchMethodException e) {
    return false;
  }
}

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

public static boolean checkZeroArgConstructor(Class clazz) {
  try {
    clazz.getDeclaredConstructor();
    return true;
  } catch (NoSuchMethodException e) {
    return false;
  }
}

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

/**
 * Obtain an accessible constructor for the given class and parameters.
 * @param clazz the clazz to check
 * @param parameterTypes the parameter types of the desired constructor
 * @return the constructor reference
 * @throws NoSuchMethodException if no such constructor exists
 * @since 5.0
 */
public static <T> Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
    throws NoSuchMethodException {
  Constructor<T> ctor = clazz.getDeclaredConstructor(parameterTypes);
  makeAccessible(ctor);
  return ctor;
}

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

public static Constructor getConstructor(Class type, Class[] parameterTypes) {
  try {
    Constructor constructor = type.getDeclaredConstructor(parameterTypes);
    constructor.setAccessible(true);
    return constructor;
  }
  catch (NoSuchMethodException e) {
    throw new CodeGenerationException(e);
  }
}

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

protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor) {
  Class<?> declaringClass = constructor.getDeclaringClass();
  Class<?> userClass = ClassUtils.getUserClass(declaringClass);
  if (userClass != declaringClass) {
    try {
      return userClass.getDeclaredConstructor(constructor.getParameterTypes());
    }
    catch (NoSuchMethodException ex) {
      // No equivalent constructor on user class (superclass)...
      // Let's proceed with the given constructor as we usually would.
    }
  }
  return constructor;
}

代码示例来源:origin: org.mockito/mockito-core

private static Constructor<?> noArgConstructorOf(Class<?> type) {
  Constructor<?> constructor;
  try {
    constructor = type.getDeclaredConstructor();
  } catch (NoSuchMethodException e) {
    throw new MockitoException("Please ensure that the type '" + type.getSimpleName() + "' has a no-arg constructor.");
  }
  return constructor;
}

代码示例来源:origin: alibaba/druid

public static XAConnection createXAConnection(Object factory, Connection physicalConn) throws SQLException {
  try {
    if (constructor == null) {
      constructor = JdbcXAConnection.class.getDeclaredConstructor(JdbcDataSourceFactory.class, int.class,
                                JdbcConnection.class);
      constructor.setAccessible(true);
    }
    int id = getNextId(XA_DATA_SOURCE);
    return constructor.newInstance(factory, id, physicalConn);
  } catch (Exception e) {
    throw new SQLException("createXAConnection error", e);
  }
}

代码示例来源:origin: square/retrofit

@Override Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object,
  @Nullable Object... args) throws Throwable {
 // Because the service interface might not be public, we need to use a MethodHandle lookup
 // that ignores the visibility of the declaringClass.
 Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
 constructor.setAccessible(true);
 return constructor.newInstance(declaringClass, -1 /* trusted */)
   .unreflectSpecial(method, declaringClass)
   .bindTo(object)
   .invokeWithArguments(args);
}

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

private Member resolveMember() {
  ClassLoader loader = this.clazz.getClassLoader();
  Class<?>[] argTypes = new Class<?>[this.args.length];
  for (int i = 0; i < this.args.length; i++) {
    argTypes[i] = ClassUtils.resolveClassName(this.args[i].getClassName(), loader);
  }
  try {
    if (CONSTRUCTOR.equals(this.name)) {
      return this.clazz.getDeclaredConstructor(argTypes);
    }
    return this.clazz.getDeclaredMethod(this.name, argTypes);
  }
  catch (NoSuchMethodException ex) {
    throw new IllegalStateException("Method [" + this.name +
        "] was discovered in the .class file but cannot be resolved in the class object", ex);
  }
}

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

private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
    inputStream.defaultReadObject();
    try {
      if (this.methodName != null) {
        this.methodParameter = new MethodParameter(
            this.declaringClass.getDeclaredMethod(this.methodName, this.parameterTypes), this.parameterIndex);
      }
      else {
        this.methodParameter = new MethodParameter(
            this.declaringClass.getDeclaredConstructor(this.parameterTypes), this.parameterIndex);
      }
    }
    catch (Throwable ex) {
      throw new IllegalStateException("Could not find original class structure", ex);
    }
  }
}

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

/** Returns a {@link Constructor} that represents the constructor for the supplied class which takes the supplied parameter
 * types. */
static public Constructor getDeclaredConstructor (Class c, Class... parameterTypes) throws ReflectionException {
  try {
    return new Constructor(c.getDeclaredConstructor(parameterTypes));
  } catch (SecurityException e) {
    throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
  } catch (NoSuchMethodException e) {
    throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
  }
}

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

/** Returns a {@link Constructor} that represents the constructor for the supplied class which takes the supplied parameter
 * types. */
static public Constructor getDeclaredConstructor (Class c, Class... parameterTypes) throws ReflectionException {
  try {
    return new Constructor(c.getDeclaredConstructor(parameterTypes));
  } catch (SecurityException e) {
    throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
  } catch (NoSuchMethodException e) {
    throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
  }
}

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

static Invokable<?, Prepender> constructor(Class<?>... parameterTypes) throws Exception {
 Constructor<Prepender> constructor = Prepender.class.getDeclaredConstructor(parameterTypes);
 return Invokable.from(constructor);
}

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

static Element constructor() throws Exception {
 Constructor<?> constructor = A.class.getDeclaredConstructor(Object.class);
 Element element = new Element(constructor);
 assertEquals(constructor.getName(), element.getName());
 assertEquals(A.class, element.getDeclaringClass());
 return element;
}

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

public void testConstructor_Ignored_ShouldPass() throws Exception {
 new NullPointerTester()
   .ignore(FailOnOneOfTwoConstructors.class.getDeclaredConstructor(String.class))
   .testAllPublicConstructors(FailOnOneOfTwoConstructors.class);
}

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

@Test
public void forConstructor() throws Exception {
  Constructor<?> constructor = Constructors.class.getDeclaredConstructor(List.class);
  Type type = SerializableTypeWrapper.forMethodParameter(MethodParameter.forExecutable(constructor, 0));
  assertThat(type.toString(), equalTo("java.util.List<java.lang.String>"));
  assertSerializable(type);
}

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

private void emitDefaultConstructor(ClassEmitter ce) {
  Constructor<Object> declaredConstructor;
  try {
    declaredConstructor = Object.class.getDeclaredConstructor();
  }
  catch (NoSuchMethodException e) {
    throw new IllegalStateException("Object should have default constructor ", e);
  }
  MethodInfo constructor = (MethodInfo) MethodInfoTransformer.getInstance().transform(declaredConstructor);
  CodeEmitter e = EmitUtils.begin_method(ce, constructor, Constants.ACC_PUBLIC);
  e.load_this();
  e.dup();
  Signature sig = constructor.getSignature();
  e.super_invoke_constructor(sig);
  e.return_value();
  e.end_method();
}

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

@Test
public void annotatedConstructorParameterInStaticNestedClass() throws Exception {
  Constructor<?> constructor = NestedClass.class.getDeclaredConstructor(String.class);
  MethodParameter methodParameter = MethodParameter.forExecutable(constructor, 0);
  assertEquals(String.class, methodParameter.getParameterType());
  assertNotNull("Failed to find @Param annotation", methodParameter.getParameterAnnotation(Param.class));
}

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

public void testConstructor_returnType_hasTypeParameter() throws Exception {
 @SuppressWarnings("rawtypes") // Foo.class for Foo<T> is always raw type
 Class<WithConstructorAndTypeParameter> type = WithConstructorAndTypeParameter.class;
 @SuppressWarnings("rawtypes") // Foo.class
 Constructor<WithConstructorAndTypeParameter> constructor = type.getDeclaredConstructor();
 Invokable<?, ?> factory = Invokable.from(constructor);
 assertThat(factory.getTypeParameters()).hasLength(2);
 assertEquals(type.getTypeParameters()[0], factory.getTypeParameters()[0]);
 assertEquals(constructor.getTypeParameters()[0], factory.getTypeParameters()[1]);
 ParameterizedType returnType = (ParameterizedType) factory.getReturnType().getType();
 assertEquals(type, returnType.getRawType());
 assertEquals(
   ImmutableList.copyOf(type.getTypeParameters()),
   ImmutableList.copyOf(returnType.getActualTypeArguments()));
}

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

public void testConstructor_isOverridablel() throws Exception {
 Invokable<?, ?> delegate = Invokable.from(Foo.class.getDeclaredConstructor());
 assertFalse(delegate.isOverridable());
 assertFalse(delegate.isVarArgs());
}

相关文章

微信公众号

最新文章

更多

Class类方法