java.lang.reflect.Constructor.newInstance()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.1k)|赞(0)|评价(0)|浏览(240)

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

Constructor.newInstance介绍

[英]Returns a new instance of the declaring class, initialized by dynamically invoking the constructor represented by this Constructor object. This reproduces the effect of new declaringClass(arg1, arg2, ... , This method performs the following:

  • A new instance of the declaring class is created. If the declaring class cannot be instantiated (i.e. abstract class, an interface, an array type, or a primitive type) then an InstantiationException is thrown.

  • If this Constructor object is enforcing access control (see AccessibleObject) and this constructor is not accessible from the current context, an IllegalAccessException is thrown.

  • If the number of arguments passed and the number of parameters do not match, an IllegalArgumentException is thrown.

  • For each argument passed:

  • If the corresponding parameter type is a primitive type, the argument is unboxed. If the unboxing fails, an IllegalArgumentException is thrown.

    • If the resulting argument cannot be converted to the parameter type via a widening conversion, an IllegalArgumentException is thrown.
  • The constructor represented by this Constructor object is then invoked. If an exception is thrown during the invocation, it is caught and wrapped in an InvocationTargetException. This exception is then thrown. If the invocation completes normally, the newly initialized object is returned.
    [中]返回声明类的新实例,该实例通过动态调用此构造函数对象表示的构造函数初始化。这将再现新的去极化类(arg1、arg2,…)的效果,此方法执行以下操作:
    *将创建声明类的新实例。如果无法实例化声明类(即抽象类、接口、数组类型或基元类型),则抛出InstanceionException。
    *如果此构造函数对象正在强制访问控制(请参见AccessibleObject),并且无法从当前上下文访问此构造函数,则会引发IllegaAccessException。
    *如果传递的参数数量与参数数量不匹配,则抛出IllegalArgumentException。
    *对于通过的每个参数:
    *如果对应的参数类型是基元类型,则参数将取消绑定。如果取消装箱失败,将抛出IllegalArgumentException。
    *如果无法通过加宽转换将结果参数转换为参数类型,则会引发IllegalArgumentException。
    *然后调用此构造函数对象表示的构造函数。如果在调用期间引发异常,则会捕获该异常并将其包装在InvocationTargetException中。然后抛出此异常。如果调用正常完成,则返回新初始化的对象。

代码示例

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

protected Object instantiate()
    throws Exception {
  return _constructor.newInstance(_constructorArgs);
}

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

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  Object retVal = invocation.proceed();
  Assert.state(this.applicationEventClassConstructor != null, "No ApplicationEvent class set");
  ApplicationEvent event = (ApplicationEvent)
      this.applicationEventClassConstructor.newInstance(invocation.getThis());
  Assert.state(this.applicationEventPublisher != null, "No ApplicationEventPublisher available");
  this.applicationEventPublisher.publishEvent(event);
  return retVal;
}

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

public ClassLoader getThrowawayClassLoader() {
  try {
    Object classFinder = this.getClassFinderMethod.invoke(this.classLoader);
    Object parent = this.getParentMethod.invoke(this.classLoader);
    // arguments for 'clone'-like method
    return (ClassLoader) this.wlGenericClassLoaderConstructor.newInstance(classFinder, parent);
  }
  catch (InvocationTargetException ex) {
    throw new IllegalStateException("WebLogic GenericClassLoader constructor failed", ex.getCause());
  }
  catch (Throwable ex) {
    throw new IllegalStateException("Could not construct WebLogic GenericClassLoader", ex);
  }
}

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

public CertificateChainCleaner buildCertificateChainCleaner(X509TrustManager trustManager) {
 try {
  Class<?> extensionsClass = Class.forName("android.net.http.X509TrustManagerExtensions");
  Constructor<?> constructor = extensionsClass.getConstructor(X509TrustManager.class);
  Object extensions = constructor.newInstance(trustManager);
  Method checkServerTrusted = extensionsClass.getMethod(
    "checkServerTrusted", X509Certificate[].class, String.class, String.class);
  return new AndroidCertificateChainCleaner(extensions, checkServerTrusted);
 } catch (Exception e) {
  throw new AssertionError(e);
 }
}

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

@Override
final Object invokeInternal(@Nullable Object receiver, Object[] args)
  throws InvocationTargetException, IllegalAccessException {
 try {
  return constructor.newInstance(args);
 } catch (InstantiationException e) {
  throw new RuntimeException(constructor + " failed.", e);
 }
}

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

private Object createNewDelegate() {
  try {
    return ReflectionUtils.accessibleConstructor(this.defaultImplType).newInstance();
  }
  catch (Throwable ex) {
    throw new IllegalArgumentException("Cannot create default implementation for '" +
        this.interfaceType.getName() + "' mixin (" + this.defaultImplType.getName() + "): " + ex);
  }
}

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

private Writer newInstance(Object webSocket, boolean isProtected) {
    try {
      return (Writer) constructor.newInstance(webSocket, null, isProtected);
    }
    catch (Exception ex) {
      throw new HandshakeFailureException("Failed to create TyrusServletWriter", ex);
    }
  }
}

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

private Writer newServletWriter(TyrusHttpUpgradeHandler handler) {
  try {
    return (Writer) constructor.newInstance(handler);
  }
  catch (Exception ex) {
    throw new HandshakeFailureException("Failed to instantiate TyrusServletWriter", ex);
  }
}

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

protected Object instantiate()
  throws Exception {
  try {
    if (_constructor != null)
      return _constructor.newInstance(_constructorArgs);
    else
      return _type.newInstance();
  } catch (Exception e) {
    throw new HessianProtocolException("'" + _type.getName() + "' could not be instantiated", e);
  }
}

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

private Object create(long initValue)
      throws IOException {
    if (initValue == Long.MIN_VALUE)
      throw new IOException(_cl.getName() + " expects name.");

    try {
      return _constructor.newInstance(new Object[]{new Long(initValue)});
    } catch (Exception e) {
      throw new IOExceptionWrapper(e);
    }
  }
}

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

private Object create(String value)
      throws IOException {
    if (value == null)
      throw new IOException(_cl.getName() + " expects name.");

    try {
      return _constructor.newInstance(new Object[]{value});
    } catch (Exception e) {
      throw new IOExceptionWrapper(e);
    }
  }
}

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

static ByteBuffer newDirectBuffer(long address, int capacity) {
  ObjectUtil.checkPositiveOrZero(capacity, "capacity");
  try {
    return (ByteBuffer) DIRECT_BUFFER_CONSTRUCTOR.newInstance(address, capacity);
  } catch (Throwable cause) {
    // Not expected to ever throw!
    if (cause instanceof Error) {
      throw (Error) cause;
    }
    throw new Error(cause);
  }
}

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

@SuppressWarnings("unchecked")
private static <T> T instantiateFactory(String instanceClassName, Class<T> factoryClass, ClassLoader classLoader) {
  try {
    Class<?> instanceClass = ClassUtils.forName(instanceClassName, classLoader);
    if (!factoryClass.isAssignableFrom(instanceClass)) {
      throw new IllegalArgumentException(
          "Class [" + instanceClassName + "] is not assignable to [" + factoryClass.getName() + "]");
    }
    return (T) ReflectionUtils.accessibleConstructor(instanceClass).newInstance();
  }
  catch (Throwable ex) {
    throw new IllegalArgumentException("Unable to instantiate factory class: " + factoryClass.getName(), ex);
  }
}

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

public void setCustomSqlExceptionTranslatorClass(@Nullable Class<? extends SQLExceptionTranslator> customTranslatorClass) {
  if (customTranslatorClass != null) {
    try {
      this.customSqlExceptionTranslator =
          ReflectionUtils.accessibleConstructor(customTranslatorClass).newInstance();
    }
    catch (Throwable ex) {
      throw new IllegalStateException("Unable to instantiate custom translator", ex);
    }
  }
  else {
    this.customSqlExceptionTranslator = null;
  }
}

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

@Override
public T newChannel() {
  try {
    return constructor.newInstance();
  } catch (Throwable t) {
    throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
  }
}

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

public ClassLoader getThrowawayClassLoader() {
  try {
    ClassLoader loader = this.cloneConstructor.newInstance(getClassLoader());
    // Clear out the transformers (copied as well)
    List<?> list = (List<?>) this.transformerList.get(loader);
    list.clear();
    return loader;
  }
  catch (InvocationTargetException ex) {
    throw new IllegalStateException("WebSphere CompoundClassLoader constructor failed", ex.getCause());
  }
  catch (Throwable ex) {
    throw new IllegalStateException("Could not construct WebSphere CompoundClassLoader", ex);
  }
}

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

private Object newInstance(HttpServletRequest request, @Nullable Object httpSocket) {
  try {
    Object[] args = new Object[] {httpSocket, null, subjectHelper.getSubject(request)};
    return constructor.newInstance(args);
  }
  catch (Exception ex) {
    throw new HandshakeFailureException("Failed to create TyrusMuxableWebSocket", ex);
  }
}

代码示例来源: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

/**
 * Initialize the wrapped Servlet instance.
 * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
 */
@Override
public void afterPropertiesSet() throws Exception {
  if (this.servletClass == null) {
    throw new IllegalArgumentException("'servletClass' is required");
  }
  if (this.servletName == null) {
    this.servletName = this.beanName;
  }
  this.servletInstance = ReflectionUtils.accessibleConstructor(this.servletClass).newInstance();
  this.servletInstance.init(new DelegatingServletConfig());
}

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

/**
 * Create an instance of the specified job class.
 * <p>Can be overridden to post-process the job instance.
 * @param bundle the TriggerFiredBundle from which the JobDetail
 * and other info relating to the trigger firing can be obtained
 * @return the job instance
 * @throws Exception if job instantiation failed
 */
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
  Class<?> jobClass = bundle.getJobDetail().getJobClass();
  return ReflectionUtils.accessibleConstructor(jobClass).newInstance();
}

相关文章

微信公众号

最新文章

更多