javax.enterprise.inject.spi.Bean.getBeanClass()方法的使用及代码示例

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

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

Bean.getBeanClass介绍

[英]The bean Class of the managed bean or session bean or of the bean that declares the producer method or field.
[中]托管bean或会话bean或声明生产者方法或字段的bean的bean类。

代码示例

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

/**
 * Constructor that creates a new class injector for the given class.
 *
 * @param bean      information about the injected class.
 * @param resolvers all resolvers which are registered in the application.
 */
JerseyInstanceInjector(Bean<T> bean, Collection<InjectionResolver> resolvers) {
  this.bean = bean;
  this.cachedFields = analyzeFields(bean.getBeanClass(), resolvers);
}

代码示例来源:origin: HotswapProjects/HotswapAgent

private static boolean fullSignatureChanged(Bean<?> bean, Map<String, String> oldFullSignatures) {
  try {
    String newSignature = ClassSignatureComparerHelper.getJavaClassSignature(bean.getBeanClass(), ClassSignatureElement.values());
    String oldSignature = oldFullSignatures.get(bean.getBeanClass().getName());
    return oldSignature != null && newSignature != null && !oldSignature.equals(newSignature);
  } catch (Exception e) {
    LOGGER.error("Full signature evaluation failed beanClass='{}'", e, bean.getBeanClass().getName());
  }
  return true;
}

代码示例来源:origin: HotswapProjects/HotswapAgent

private static boolean fullSignatureChanged(Bean<?> bean, Map<String, String> oldFullSignatures) {
  try {
    String newSignature = ClassSignatureComparerHelper.getJavaClassSignature(bean.getBeanClass(), ClassSignatureElement.values());
    String oldSignature = oldFullSignatures.get(bean.getBeanClass().getName());
    return oldSignature != null && newSignature != null && !oldSignature.equals(newSignature);
  } catch (Exception e) {
    LOGGER.error("Full signature evaluation failed beanClass='{}'", e, bean.getBeanClass().getName());
  }
  return true;
}

代码示例来源:origin: lettuce-io/lettuce-core

private void register(AfterBeanDiscovery afterBeanDiscovery, Set<Annotation> qualifiers, Bean<?> bean) {
    LOGGER.info(String.format("Registering bean '%s' with qualifiers %s.", bean.getBeanClass().getName(), qualifiers));
    afterBeanDiscovery.addBean(bean);
  }
}

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

@Override
@SuppressWarnings("unchecked")
public <T> List<ServiceHolder<T>> getAllServiceHolders(Class<T> contractOrImpl, Annotation... qualifiers) {
  List<ServiceHolder<T>> result = new ArrayList<>();
  for (Bean<?> bean : beanManager.getBeans(contractOrImpl, qualifiers)) {
    CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
    T reference = (T) beanManager.getReference(bean, contractOrImpl, ctx);
    int rank = 1;
    if (bean instanceof JerseyBean) {
      rank = ((JerseyBean) bean).getRank();
    }
    result.add(new ServiceHolderImpl<>(reference, (Class<T>) bean.getBeanClass(), bean.getTypes(), rank));
  }
  return result;
}

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

@Override
public Object create(final String ref, Class<?> cls, final ClassLoader classLoader) throws Exception {
  final BeanManager beanManager = getBeanManager();
  final Bean<?> bean = getBean(ref, beanManager);
  if (bean == null) {
    return null;
  }
  final CreationalContext<?> context = beanManager.createCreationalContext(bean);
  final Object result = beanManager.getReference(bean, bean.getBeanClass(), context);
  contexts.put(result, new Holder(bean, context));
  return result;
}

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

@Override
public Class<?> getArtifactClass(final String ref, final ClassLoader classLoader) {
  final Bean<?> bean = getBean(ref, getBeanManager());
  return bean == null ? null : bean.getBeanClass();
}

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

private InjectionTarget getInjectionTarget(Class<?> clazz) {
  InjectionTarget<?> target = injectionTargets.get(clazz);
  if (target != null) {
    return target;
  }
  final BeanManagerImpl beanManager = BeanManagerProxy.unwrap(beanManagerSupplier.get());
  Bean<?> bean = null;
  Set<Bean<?>> beans = new HashSet<>(beanManager.getBeans(clazz, Any.Literal.INSTANCE));
  Iterator<Bean<?>> it = beans.iterator();
  //we may have resolved some sub-classes
  //go through and remove them from the bean set
  while (it.hasNext()) {
    Bean<?> b = it.next();
    if(b.getBeanClass() != clazz) {
      it.remove();
    }
  }
  if(beans.size() == 1) {
    bean = beans.iterator().next();
  }
  InjectionTarget<?> newTarget = InjectionTargets.createInjectionTarget(clazz, bean, beanManager, true);
  target = injectionTargets.putIfAbsent(clazz, newTarget);
  if (target == null) {
    return newTarget;
  } else {
    return target;
  }
}

代码示例来源:origin: HotswapProjects/HotswapAgent

/**
 * Return all bean instances.
 *
 * @param bean the bean
 * @return the bean instances
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<Object> getBeanInstances(Bean<?> bean) {
  List<Object> result = new ArrayList<>();
  Class<? extends Context> contextClass = getContextClass(bean.getScope());
  Map beanRegistry = (Map) getBeanRegistry(contextClass);
  if (beanRegistry != null) {
    Map m = (Map) beanRegistry.get(bean.getBeanClass().getName());
    if (m != null) {
      result.addAll(m.keySet());
    } else {
      LOGGER.debug("BeanRegistry is empty for bean class '{}'", bean.getBeanClass().getName());
    }
  } else {
    LOGGER.error("BeanRegistry field not found in context class '{}'", contextClass.getName());
  }
  return result;
}

代码示例来源:origin: oracle/helidon

private DelegatingGauge<?> buildDelegatingGauge(String gaugeName, AnnotatedMethodConfigurator<?> site, BeanManager bm) {
  Bean<?> bean = bm.getBeans(site.getAnnotated().getJavaMember().getDeclaringClass())
      .stream()
      .findFirst()
      .orElseThrow(() -> new IllegalArgumentException("Cannot find bean for annotated gauge " + gaugeName));
  return DelegatingGauge.newInstance(
      site.getAnnotated().getJavaMember(),
      getReference(bm, bean.getBeanClass(), bean),
      site.getAnnotated().getJavaMember().getReturnType());
}

代码示例来源:origin: HotswapProjects/HotswapAgent

private void doRecreateProxy(ClassLoader classLoader, Map<Object, Object> registeredBeans, Class<?> proxyClass) {
  ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
  try {
    ProxyClassLoadingDelegate.beginProxyRegeneration();
    Class<?> proxyFactoryClass = null;
    for (Entry<Object, Object> entry : registeredBeans.entrySet()) {
      Bean<?> bean = (Bean<?>) entry.getKey();
      if (bean != null) {
        Set<Type> types = bean.getTypes();
        if (types.contains(proxyClass)) {
          Thread.currentThread().setContextClassLoader(bean.getBeanClass().getClassLoader());
          if (proxyFactoryClass == null) {
            proxyFactoryClass = classLoader.loadClass("org.jboss.weld.bean.proxy.ProxyFactory");
          }
          Object proxyFactory = entry.getValue();
          LOGGER.info("Recreate proxyClass '{}' for bean class '{}'.", proxyClass.getName(), bean.getClass());
          ReflectionHelper.invoke(proxyFactory, proxyFactoryClass, "getProxyClass", new Class[] {});
        }
      }
    }
  } catch (Exception e) {
    LOGGER.error("recreateProxyFactory() exception {}.", e, e.getMessage());
  } finally {
    Thread.currentThread().setContextClassLoader(oldContextClassLoader);
    ProxyClassLoadingDelegate.endProxyRegeneration();
  }
}

代码示例来源:origin: oracle/helidon

/**
 * Records metric producer fields defined by the application. Ignores producers
 * with non-default qualifiers and library producers.
 *
 * @param ppf Producer field.
 */
private void recordProducerFields(@Observes ProcessProducerField<? extends org.eclipse.microprofile.metrics.Metric, ?> ppf) {
  LOGGER.log(Level.FINE, () -> "### recordProducerFields " + ppf.getBean().getBeanClass());
  if (!MetricProducer.class.equals(ppf.getBean().getBeanClass())) {
    Metric metric = ppf.getAnnotatedProducerField().getAnnotation(Metric.class);
    if (metric != null) {
      Optional<? extends Annotation> hasQualifier
          = ppf.getAnnotatedProducerField()
          .getAnnotations()
          .stream()
          .filter(annotation -> annotation.annotationType().isAnnotationPresent(Qualifier.class))
          .findFirst();
      // Ignore producers with non-default qualifiers
      if (!hasQualifier.isPresent() || hasQualifier.get() instanceof Default) {
        producers.put(ppf.getBean(), ppf.getAnnotatedProducerField());
      }
    }
  }
}

代码示例来源:origin: oracle/helidon

/**
 * Records metric producer methods defined by the application. Ignores producers
 * with non-default qualifiers and library producers.
 *
 * @param ppm Producer method.
 */
private void recordProducerMethods(@Observes
                      ProcessProducerMethod<? extends org.eclipse.microprofile.metrics.Metric, ?> ppm) {
  LOGGER.log(Level.FINE, () -> "### recordProducerMethods " + ppm.getBean().getBeanClass());
  if (!MetricProducer.class.equals(ppm.getBean().getBeanClass())) {
    Metric metric = ppm.getAnnotatedProducerMethod().getAnnotation(Metric.class);
    if (metric != null) {
      Optional<? extends Annotation> hasQualifier
          = ppm.getAnnotatedProducerMethod()
          .getAnnotations()
          .stream()
          .filter(annotation -> annotation.annotationType().isAnnotationPresent(Qualifier.class))
          .findFirst();
      // Ignore producers with non-default qualifiers
      if (!hasQualifier.isPresent() || hasQualifier.get() instanceof Default) {
        producers.put(ppm.getBean(), ppm.getAnnotatedProducerMethod());
      }
    }
  }
}

代码示例来源:origin: HotswapProjects/HotswapAgent

private static EnhancedAnnotatedType<?> createAnnotatedTypeForExistingBeanClass(String bdaId, Bean<?> bean) {
  ClassTransformer classTransformer = getClassTransformer();
  SlimAnnotatedType<?> annotatedType = classTransformer.getBackedAnnotatedType(bean.getBeanClass(), bdaId);
  return EnhancedAnnotatedTypeImpl.of(annotatedType, classTransformer);
}

代码示例来源:origin: HotswapProjects/HotswapAgent

if (bean.getBeanClass().isInterface()) {
  continue;
  LOGGER.debug("Skipping bean redefinition. Bean '{}' signature was not changed.", bean.getBeanClass().getName());
  continue;
  if (isReinjectingContext(bean)) {
    doReloadInjectionTargetBean(beanManager, (InjectionTargetBean) bean, oldSignatures, reloadStrategy);
    LOGGER.debug("Bean reloaded '{}'.", bean.getBeanClass().getName());
  } else {
    LOGGER.info("Bean '{}' redefined.", bean.getBeanClass().getName());
  LOGGER.warning("Class '{}' reloading not supported.", bean.getBeanClass().getName());

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

@Override
public void inject(T instance, CreationalContext<T> ctx) {
  /*
   * If an instance contains any fields which be injected by Jersey then Jersey attempts to inject them using annotations
   * retrieves from registered InjectionResolvers.
   */
  try {
    injector.get().inject(instance);
  } catch (Throwable cause) {
    throw new InjectionException(
        "Exception occurred during Jersey/JAX-RS annotations processing in the class: " + bean.getBeanClass(), cause);
  }
  /*
   * The rest of the fields (annotated by @Inject) are injected using CDI.
   */
  super.inject(instance, ctx);
}

代码示例来源:origin: HotswapProjects/HotswapAgent

if (bean.getBeanClass().isInterface()) {
  continue;
  LOGGER.debug("Skipping bean redefinition. Bean '{}' signature was not changed.", bean.getBeanClass().getName());
  continue;
    if (isReinjectingContext(bean)) {
      doReloadAbstractClassBean(beanManager, (AbstractClassBean) bean, oldSignatures, reloadStrategy);
      LOGGER.debug("Bean reloaded '{}'", bean.getBeanClass().getName());
      continue;
  LOGGER.info("Bean '{}' redefined", bean.getBeanClass().getName());
} else {
  LOGGER.warning("Bean '{}' reloading not supported.", bean.getBeanClass().getName());

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

/**
 * Returns the injectee for a field.
 *
 * @param bean bean in which the field is placed.
 * @param field      the field to analyze.
 * @return the list (in order) of parameters to the constructor.
 */
private static Injectee getFieldInjectee(Bean<?> bean, Field field) {
  Set<Annotation> annotations = Arrays.stream(field.getAnnotations())
      .collect(ImmutableCollectors.toImmutableSet());
  Type adjustedType = ReflectionUtils.resolveField(bean.getBeanClass(), field);
  InjecteeImpl injectee = new InjecteeImpl();
  injectee.setParentClassScope(bean.getScope());
  if (isProvider(adjustedType)) {
    ParameterizedType paramType = (ParameterizedType) adjustedType;
    injectee.setRequiredType(paramType.getActualTypeArguments()[0]);
    injectee.setProvider(true);
  } else {
    injectee.setRequiredType(adjustedType);
  }
  injectee.setParent(field);
  injectee.setRequiredQualifiers(getFieldAdjustedQualifierAnnotations(field, annotations));
  return injectee;
}

代码示例来源:origin: resteasy/Resteasy

private void addSessionBeanInterface(Bean<?> bean)
{
 for (Type type : bean.getTypes())
 {
   if ((type instanceof Class<?>) && ((Class<?>) type).isInterface())
   {
    Class<?> clazz = (Class<?>) type;
    if (Utils.isJaxrsAnnotatedClass(clazz))
    {
      sessionBeanInterface.put(bean.getBeanClass(), type);
      LogMessages.LOGGER.debug(Messages.MESSAGES.typeWillBeUsedForLookup(type, bean.getBeanClass()));
      return;
    }
   }
 }
 LogMessages.LOGGER.debug(Messages.MESSAGES.noLookupInterface(bean.getBeanClass()));
}

代码示例来源:origin: resteasy/Resteasy

/**
* Observes ProcessSessionBean events and creates a (Bean class {@literal ->} Local
* interface) map for Session beans with local interfaces. This map is
* necessary since RESTEasy identifies a bean class as JAX-RS components
* while CDI requires a local interface to be used for lookup.
*
* @param <T> type
* @param event event
*
*/
public <T> void observeSessionBeans(@Observes ProcessSessionBean<T> event)
{
 Bean<Object> sessionBean = event.getBean();
 if (Utils.isJaxrsComponent(sessionBean.getBeanClass()))
 {
   addSessionBeanInterface(sessionBean);
 }
}

相关文章