Java 类org.springframework.util.ClassUtils 实例源码

项目:lams    文件:ProxyFactoryBean.java   
/**
 * Return the singleton instance of this class's proxy object,
 * lazily creating it if it hasn't been created already.
 * @return the shared singleton proxy
 */
private synchronized Object getSingletonInstance() {
    if (this.singletonInstance == null) {
        this.targetSource = freshTargetSource();
        if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
            // Rely on AOP infrastructure to tell us what interfaces to proxy.
            Class<?> targetClass = getTargetClass();
            if (targetClass == null) {
                throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
            }
            setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
        }
        // Initialize the shared singleton instance.
        super.setFrozen(this.freezeProxy);
        this.singletonInstance = getProxy(createAopProxy());
    }
    return this.singletonInstance;
}
项目:spring-data-jdbc    文件:GeneratedValueUtil.java   
private static String getNumberConversionMethodName(Class<?> objectClass) {
    objectClass = ClassUtils.resolvePrimitiveIfNecessary(objectClass);
    if (Integer.class.isAssignableFrom(objectClass)) {
        return INT_VALUE;
    }
    if (Long.class.isAssignableFrom(objectClass)) {
        return LONG_VALUE;
    }
    if (Float.class.isAssignableFrom(objectClass)) {
        return FLOAT_VALUE;
    }
    if (Double.class.isAssignableFrom(objectClass)) {
        return DOUBLE_VALUE;
    }
    throw new IllegalArgumentException(
            "Cannot get conversion number for class " + objectClass);
}
项目:bekit    文件:FlowParser.java   
private static FlowExecutor.TargetMappingExecutor parseTargetMapping(Method method) {
    logger.debug("解析目标对象映射方法:{}", method);
    // 校验方法类型
    if (!Modifier.isPublic(method.getModifiers())) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型");
    }
    // 校验入参
    Class[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "必须只能有一个入参");
    }
    // 校验返回参数
    if (method.getReturnType() != String.class) {
        throw new IllegalArgumentException("目标对象映射方法" + ClassUtils.getQualifiedMethodName(method) + "返回参数必须是String类型");
    }

    return new FlowExecutor.TargetMappingExecutor(method, parameterTypes[0]);
}
项目:cas-5.1.0    文件:CasCoreBootstrapStandaloneConfiguration.java   
@ConfigurationPropertiesBinding
@Bean
public Converter<String, List<Class<? extends Throwable>>> commaSeparatedStringToThrowablesCollection() {
    return new Converter<String, List<Class<? extends Throwable>>>() {
        @Override
        public List<Class<? extends Throwable>> convert(final String source) {
            try {
                final List<Class<? extends Throwable>> classes = new ArrayList<>();
                for (final String className : StringUtils.commaDelimitedListToStringArray(source)) {
                    classes.add((Class<? extends Throwable>) ClassUtils.forName(className.trim(), getClass().getClassLoader()));
                }
                return classes;
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    };
}
项目:lams    文件:ProxyFactoryBean.java   
/**
 * Create a new prototype instance of this class's created proxy object,
 * backed by an independent AdvisedSupport configuration.
 * @return a totally independent proxy, whose advice we may manipulate in isolation
 */
private synchronized Object newPrototypeInstance() {
    // In the case of a prototype, we need to give the proxy
    // an independent instance of the configuration.
    // In this case, no proxy will have an instance of this object's configuration,
    // but will have an independent copy.
    if (logger.isTraceEnabled()) {
        logger.trace("Creating copy of prototype ProxyFactoryBean config: " + this);
    }

    ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());
    // The copy needs a fresh advisor chain, and a fresh TargetSource.
    TargetSource targetSource = freshTargetSource();
    copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());
    if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
        // Rely on AOP infrastructure to tell us what interfaces to proxy.
        copy.setInterfaces(
                ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), this.proxyClassLoader));
    }
    copy.setFrozen(this.freezeProxy);

    if (logger.isTraceEnabled()) {
        logger.trace("Using ProxyCreatorSupport copy: " + copy);
    }
    return getProxy(copy.createAopProxy());
}
项目:spring-domain-events    文件:PublicationTargetIdentifier.java   
/**
 * Creates a {@link PublicationTargetIdentifier} for the given {@link Method}.
 * 
 * @param method must not be {@literal null}.
 * @return
 */
public static PublicationTargetIdentifier forMethod(Method method) {

    String typeName = ClassUtils.getUserClass(method.getDeclaringClass()).getName();
    String methodName = method.getName();
    String parameterTypes = StringUtils.arrayToDelimitedString(method.getParameterTypes(), ", ");

    return PublicationTargetIdentifier.of(String.format("%s.%s(%s)", typeName, methodName, parameterTypes));
}
项目:lams    文件:ExtendedEntityManagerCreator.java   
/**
 * Actually create the EntityManager proxy.
 * @param rawEm raw EntityManager
 * @param emIfc the (potentially vendor-specific) EntityManager
 * interface to proxy, or {@code null} for default detection of all interfaces
 * @param cl the ClassLoader to use for proxy creation (maybe {@code null})
 * @param exceptionTranslator the PersistenceException translator to use
 * @param jta whether to create a JTA-aware EntityManager
 * (or {@code null} if not known in advance)
 * @param containerManaged whether to follow container-managed EntityManager
 * or application-managed EntityManager semantics
 * @param synchronizedWithTransaction whether to automatically join ongoing
 * transactions (according to the JPA 2.1 SynchronizationType rules)
 * @return the EntityManager proxy
 */
private static EntityManager createProxy(
        EntityManager rawEm, Class<? extends EntityManager> emIfc, ClassLoader cl,
        PersistenceExceptionTranslator exceptionTranslator, Boolean jta,
        boolean containerManaged, boolean synchronizedWithTransaction) {

    Assert.notNull(rawEm, "EntityManager must not be null");
    Set<Class<?>> ifcs = new LinkedHashSet<Class<?>>();
    if (emIfc != null) {
        ifcs.add(emIfc);
    }
    else {
        ifcs.addAll(ClassUtils.getAllInterfacesForClassAsSet(rawEm.getClass(), cl));
    }
    ifcs.add(EntityManagerProxy.class);
    return (EntityManager) Proxy.newProxyInstance(
            (cl != null ? cl : ExtendedEntityManagerCreator.class.getClassLoader()),
            ifcs.toArray(new Class<?>[ifcs.size()]),
            new ExtendedEntityManagerInvocationHandler(
                    rawEm, exceptionTranslator, jta, containerManaged, synchronizedWithTransaction));
}
项目:spring-data-documentdb    文件:DocumentDbConfigurationSupport.java   
protected Set<Class<?>> scanForEntities(String basePackage) throws ClassNotFoundException {
    if (!StringUtils.hasText(basePackage)) {
        return Collections.emptySet();
    }

    final Set<Class<?>> initialEntitySet = new HashSet<Class<?>>();

    if (StringUtils.hasText(basePackage)) {
        final ClassPathScanningCandidateComponentProvider componentProvider =
                new ClassPathScanningCandidateComponentProvider(false);
        componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));

        for (final BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {

            initialEntitySet
                    .add(ClassUtils.forName(candidate.getBeanClassName(),
                            DocumentDbConfigurationSupport.class.getClassLoader()));
        }
    }

    return initialEntitySet;
}
项目:wamp2spring    文件:HandlerMethodService.java   
public HandlerMethodService(ConversionService conversionService,
        List<HandlerMethodArgumentResolver> customArgumentResolvers,
        ObjectMapper objectMapper, ApplicationContext applicationContext) {
    this.conversionService = conversionService;
    this.parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    this.argumentResolvers = new HandlerMethodArgumentResolverComposite();

    ConfigurableBeanFactory beanFactory = ClassUtils.isAssignableValue(
            ConfigurableApplicationContext.class, applicationContext)
                    ? ((ConfigurableApplicationContext) applicationContext)
                            .getBeanFactory()
                    : null;

    this.argumentResolvers.addResolver(
            new HeaderMethodArgumentResolver(this.conversionService, beanFactory));
    this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver());
    this.argumentResolvers.addResolver(new WampMessageMethodArgumentResolver());
    this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver());
    this.argumentResolvers.addResolver(new WampSessionIdMethodArgumentResolver());
    this.argumentResolvers.addResolvers(customArgumentResolvers);

    this.objectMapper = objectMapper;
}
项目:wamp2spring    文件:InvocableHandlerMethod.java   
/**
 * Invoke the method after resolving its argument values in the context of the given
 * message.
 * <p>
 * Argument values are commonly resolved through
 * {@link HandlerMethodArgumentResolver}s. The {@code providedArgs} parameter however
 * may supply argument values to be used directly, i.e. without argument resolution.
 * @param message the current message being processed
 * @param arguments
 * @param argumentsKw
 * @return the raw value returned by the invoked method
 * @exception Exception raised if no suitable argument resolver can be found, or if
 * the method raised an exception
 */
@Nullable
public Object invoke(WampMessage message, List<Object> arguments,
        Map<String, Object> argumentsKw) throws Exception {
    Object[] args = getMethodArgumentValues(message, arguments, argumentsKw);
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Invoking '"
                + ClassUtils.getQualifiedMethodName(getMethod(), getBeanType())
                + "' with arguments " + Arrays.toString(args));
    }
    Object returnValue = doInvoke(args);
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Method ["
                + ClassUtils.getQualifiedMethodName(getMethod(), getBeanType())
                + "] returned [" + returnValue + "]");
    }
    return returnValue;
}
项目:leafer    文件:CachingAnnotationsAspect.java   
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();
    // The method may be on an interface, but we need attributes from the
    // target class. If the target class is null, the method will be
    // unchanged.
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
    if (targetClass == null && pjp.getTarget() != null) {
        targetClass = pjp.getTarget().getClass();
    }
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    // If we are dealing with method with generic parameters, find the
    // original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
    return specificMethod;
}
项目:tasfe-framework    文件:BaseEntity.java   
@Override
public boolean equals(Object obj) {

    if (null == obj) {
        return false;
    }

    if (this == obj) {
        return true;
    }

    if (!getClass().equals(ClassUtils.getUserClass(obj))) {
        return false;
    }

    AbstractPersistable<?> that = (AbstractPersistable<?>) obj;

    return null != this.getId() && this.getId().equals(that.getId());
}
项目:tasfe-framework    文件:NettyEmbeddedServletContainerFactory.java   
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
    ClassLoader parentClassLoader = resourceLoader != null ? resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader();
    Package nettyPackage = Bootstrap.class.getPackage();
    String title = nettyPackage.getImplementationTitle();
    String version = nettyPackage.getImplementationVersion();
    logger.info("Running with " + title + " " + version);
    NettyEmbeddedContext context = new NettyEmbeddedContext(getContextPath(), new URLClassLoader(new URL[]{}, parentClassLoader), SERVER_INFO);
    if (isRegisterDefaultServlet()) {
        logger.warn("This container does not support a default servlet");
    }
    /*if (isRegisterJspServlet()) {
        logger.warn("This container does not support a JSP servlet");
    }*/
    for (ServletContextInitializer initializer : initializers) {
        try {
            initializer.onStartup(context);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
    int port = getPort() > 0 ? getPort() : new Random().nextInt(65535 - 1024) + 1024;
    InetSocketAddress address = new InetSocketAddress(port);
    logger.info("Server initialized with port: " + port);
    return new NettyEmbeddedServletContainer(address, context);
}
项目:tasfe-framework    文件:ResourcesUtil.java   
public static URL getURL(String resourceLocation)
        throws FileNotFoundException {
    Assert.notNull(resourceLocation, "Resource location must not be null");
    if (resourceLocation.startsWith("classpath:")) {
        String path = resourceLocation.substring("classpath:".length());
        ClassLoader cl = ClassUtils.getDefaultClassLoader();
        URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
        if (url == null) {
            String description = "class path resource [" + path + "]";
            throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist");
        }

        return url;
    }
    try {
        return new URL(resourceLocation);
    } catch (MalformedURLException ex) {
        try {
            return new File(resourceLocation).toURI().toURL();
        } catch (MalformedURLException ex2) {
        }
    }
    throw new FileNotFoundException("Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path");
}
项目:bekit    文件:FlowTxParser.java   
/**
 * 解析流程事务
 *
 * @param flowTx             流程事务
 * @param transactionManager 事务管理器
 * @return 流程事务执行器
 */
public static FlowTxExecutor parseFlowTx(Object flowTx, PlatformTransactionManager transactionManager) {
    // 获取目标class(应对AOP代理情况)
    Class<?> flowTxClass = AopUtils.getTargetClass(flowTx);
    logger.debug("解析流程事务:{}", ClassUtils.getQualifiedName(flowTxClass));
    FlowTx flowTxAnnotation = flowTxClass.getAnnotation(FlowTx.class);
    // 创建流程事务执行器
    FlowTxExecutor flowTxExecutor = new FlowTxExecutor(flowTxAnnotation.flow(), flowTx, transactionManager);
    for (Method method : flowTxClass.getDeclaredMethods()) {
        for (Class clazz : FlowTxExecutor.FLOW_TX_OPERATE_ANNOTATIONS) {
            if (method.isAnnotationPresent(clazz)) {
                // 设置流程事务操作执行器
                flowTxExecutor.setOperateExecutor(clazz, parseFlowTxOperate(method));
                break;
            }
        }
    }
    flowTxExecutor.validate();

    return flowTxExecutor;
}
项目:lams    文件:AspectJAwareAdvisorAutoProxyCreator.java   
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Advice advice = this.advisor.getAdvice();
    sb.append(ClassUtils.getShortName(advice.getClass()));
    sb.append(": ");
    if (this.advisor instanceof Ordered) {
        sb.append("order ").append(((Ordered) this.advisor).getOrder()).append(", ");
    }
    if (advice instanceof AbstractAspectJAdvice) {
        AbstractAspectJAdvice ajAdvice = (AbstractAspectJAdvice) advice;
        sb.append(ajAdvice.getAspectName());
        sb.append(", declaration order ");
        sb.append(ajAdvice.getDeclarationOrder());
    }
    return sb.toString();
}
项目:spring-boot-starter-dao    文件:AbstractDataBaseBean.java   
protected final AbstractBeanDefinition createSqlSessionFactoryBean(String dataSourceName, String mapperPackage,
        String typeAliasesPackage, Dialect dialect, Configuration configuration) {
    configuration.setDatabaseId(dataSourceName);
    BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class);
    bdb.addPropertyValue("configuration", configuration);
    bdb.addPropertyValue("failFast", true);
    bdb.addPropertyValue("typeAliases", this.saenTypeAliases(typeAliasesPackage));
    bdb.addPropertyReference("dataSource", dataSourceName);
    bdb.addPropertyValue("plugins", new Interceptor[] { new CustomPageInterceptor(dialect) });
    if (!StringUtils.isEmpty(mapperPackage)) {
        try {
            mapperPackage = new StandardEnvironment().resolveRequiredPlaceholders(mapperPackage);
            String mapperPackages = ClassUtils.convertClassNameToResourcePath(mapperPackage);
            String mapperPackagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPackages + "/*.xml";
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperPackagePath);
            bdb.addPropertyValue("mapperLocations", resources);
        } catch (Exception e) {
            log.error("初始化失败", e);
            throw new RuntimeException( String.format("SqlSessionFactory 初始化失败  mapperPackage=%s", mapperPackage + ""));
        }
    }
    return bdb.getBeanDefinition();
}
项目:jwx    文件:ClasspathPackageScanner.java   
/**
 * 将符合条件的Bean以Class集合的形式返回
 * 
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public Set<Class<?>> getClassSet() throws IOException, ClassNotFoundException {
    this.classSet.clear();
    if (!this.packagesList.isEmpty()) {
        for (String pkg : this.packagesList) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                    + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = this.resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        this.classSet.add(Class.forName(className));
                    }
                }
            }
        }
    }
    return this.classSet;
}
项目:parabuild-ci    文件:SpringContainer.java   
public void addParameter(Object askFor, Object valueParam)
throws InstantiationException, IllegalAccessException {
    try {
        Class clz = ClassUtils.forName((String)askFor);
        if (log.isDebugEnabled()) {
            log.debug("trying to resolve the following class from the Spring bean container: " + clz.getName());
        }

        Map beansOfType = ((ListableBeanFactory)beanFactory).getBeansOfType(clz);
        if (log.isDebugEnabled()) {
            log.debug("beans: " + beansOfType + " - " + beansOfType.size());
        }
        if (beansOfType.size() == 0) {
            log.debug("adding parameter the normal way");
            super.addParameter(askFor, valueParam);
        } else if (beansOfType.size() > 1) {
            // TODO: handle multiple declarations
            throw new InstantiationException("multiple beans of type '" + clz.getName() + "' were found in the spring configuration");
        } else {
            this.beans.put(askFor, beansOfType.values().iterator().next());
        }
    } catch (ClassNotFoundException e) {
        super.addParameter(askFor, valueParam);
    }
}
项目:bekit    文件:ListenerParser.java   
private static ListenExecutor parseListen(Listen listenAnnotation, Method method) {
    logger.debug("解析监听方法:{}", method);
    // 校验方法类型
    if (!Modifier.isPublic(method.getModifiers())) {
        throw new IllegalArgumentException("监听方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型");
    }
    // 校验返回类型
    if (method.getReturnType() != void.class) {
        throw new IllegalArgumentException("监听方法" + ClassUtils.getQualifiedMethodName(method) + "的返回必须是void");
    }
    // 创建监听解决器
    ListenResolver resolver = (ListenResolver) ReflectUtils.newInstance(listenAnnotation.resolver());
    resolver.init(method);

    return new ListenExecutor(resolver, listenAnnotation.priorityAsc(), method);
}
项目:spring-data-tarantool    文件:MappingTarantoolConverter.java   
public Object toTarantoolNativeType(Object value, Class<?> targetType) {
    if (value instanceof Boolean ||
        value instanceof Number ||
        value instanceof String ||
        value instanceof byte[]
    ) {
        return value;
    }

    if (ClassUtils.isAssignable(Boolean.class, targetType)) {
        return conversionService.convert(value, Boolean.class);
    } else if (ClassUtils.isAssignable(Number.class, targetType)) {
        return conversionService.convert(value, Number.class);
    } else if (ClassUtils.isAssignable(String.class, targetType)) {
        return conversionService.convert(value, String.class);
    } else if (ClassUtils.isAssignable(byte[].class, targetType)) {
        return conversionService.convert(value, byte[].class);
    } else {
        throw new IllegalStateException("Unknown targetType: " + targetType);
    }
}
项目:configcenter    文件:ListenConfigModifiedResolver.java   
@Override
public void init(Method listenMethod) {
    ConfigListener configListenerAnnotation = AnnotatedElementUtils.findMergedAnnotation(listenMethod.getDeclaringClass(), ConfigListener.class);
    if (configListenerAnnotation == null) {
        throw new IllegalArgumentException("@ListenConfigModified只能标注在配置监听器(@ConfigListener)的方法上");
    }
    // 校验入参
    Class[] parameterTypes = listenMethod.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)");
    }
    if (parameterTypes[0] != List.class) {
        throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)");
    }
    ResolvableType resolvableType = ResolvableType.forMethodParameter(listenMethod, 0);
    if (resolvableType.getGeneric(0).resolve(Object.class) != ModifiedProperty.class) {
        throw new RuntimeException("监听配置被修改方法" + ClassUtils.getQualifiedMethodName(listenMethod) + "的入参必须是(List<ModifiedProperty>)");
    }
    // 设置事件类型
    ListenConfigModified listenConfigModifiedAnnotation = AnnotatedElementUtils.findMergedAnnotation(listenMethod, ListenConfigModified.class);
    eventType = new ConfigModifiedEventType(configListenerAnnotation.configContextName(), listenConfigModifiedAnnotation.prefix());
}
项目:bekit    文件:ProcessorParser.java   
/**
 * 解析处理器
 *
 * @param processor 处理器
 * @return 处理器执行器
 */
public static ProcessorExecutor parseProcessor(Object processor) {
    // 获取目标class(应对AOP代理情况)
    Class<?> processorClass = AopUtils.getTargetClass(processor);
    logger.debug("解析处理器:{}", ClassUtils.getQualifiedName(processorClass));
    // 获取处理器名称
    String processorName = processorClass.getAnnotation(Processor.class).name();
    if (StringUtils.isEmpty(processorName)) {
        processorName = ClassUtils.getShortNameAsProperty(processorClass);
    }
    // 创建处理器执行器
    ProcessorExecutor processorExecutor = new ProcessorExecutor(processorName, processor);
    for (Method method : processorClass.getDeclaredMethods()) {
        for (Class clazz : ProcessorExecutor.PROCESSOR_METHOD_ANNOTATIONS) {
            if (method.isAnnotationPresent(clazz)) {
                // 设置处理器方法执行器
                processorExecutor.setMethodExecutor(clazz, parseProcessorMethod(clazz, method));
                break;
            }
        }
    }
    processorExecutor.validate();

    return processorExecutor;
}
项目:lams    文件:ReflectiveLoadTimeWeaver.java   
/**
 * Create a new SimpleLoadTimeWeaver for the given class loader.
 * @param classLoader the {@code ClassLoader} to delegate to for
 * weaving (<i>must</i> support the required weaving methods).
 * @throws IllegalStateException if the supplied {@code ClassLoader}
 * does not support the required weaving methods
 */
public ReflectiveLoadTimeWeaver(ClassLoader classLoader) {
    Assert.notNull(classLoader, "ClassLoader must not be null");
    this.classLoader = classLoader;
    this.addTransformerMethod = ClassUtils.getMethodIfAvailable(
            this.classLoader.getClass(), ADD_TRANSFORMER_METHOD_NAME,
            new Class<?>[] {ClassFileTransformer.class});
    if (this.addTransformerMethod == null) {
        throw new IllegalStateException(
                "ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide an " +
                "'addTransformer(ClassFileTransformer)' method.");
    }
    this.getThrowawayClassLoaderMethod = ClassUtils.getMethodIfAvailable(
            this.classLoader.getClass(), GET_THROWAWAY_CLASS_LOADER_METHOD_NAME, new Class<?>[0]);
    // getThrowawayClassLoader method is optional
    if (this.getThrowawayClassLoaderMethod == null) {
        if (logger.isInfoEnabled()) {
            logger.info("The ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide a " +
                    "'getThrowawayClassLoader()' method; SimpleThrowawayClassLoader will be used instead.");
        }
    }
}
项目:juiser    文件:JuiserSpringSecurityCondition.java   
private boolean isSpringSecurityEnabled(ConditionContext ctx) {

        boolean enabled = true;

        Environment env = ctx.getEnvironment();

        for (String propName : props) {
            if (env.containsProperty(propName)) {
                if (!Boolean.parseBoolean(env.getProperty(propName))) {
                    enabled = false;
                    break;
                }
            }
        }

        if (enabled) {
            enabled = ClassUtils.isPresent(SPRING_SEC_CLASS_NAME, ctx.getClassLoader());
        }

        return enabled;
    }
项目:lams    文件:Projection.java   
private Class<?> determineCommonType(Class<?> oldType, Class<?> newType) {
    if (oldType == null) {
        return newType;
    }
    if (oldType.isAssignableFrom(newType)) {
        return oldType;
    }
    Class<?> nextType = newType;
    while (nextType != Object.class) {
        if (nextType.isAssignableFrom(oldType)) {
            return nextType;
        }
        nextType = nextType.getSuperclass();
    }
    Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(newType);
    for (Class<?> nextInterface : interfaces) {
        if (nextInterface.isAssignableFrom(oldType)) {
            return nextInterface;
        }
    }
    return Object.class;
}
项目:lams    文件:AbstractWebArgumentResolverAdapter.java   
/**
 * Delegate to the {@link WebArgumentResolver} instance.
 * @exception IllegalStateException if the resolved value is not assignable
 * to the method parameter.
 */
@Override
public Object resolveArgument(
        MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
        throws Exception {

    Class<?> paramType = parameter.getParameterType();
    Object result = this.adaptee.resolveArgument(parameter, webRequest);
    if (result == WebArgumentResolver.UNRESOLVED || !ClassUtils.isAssignableValue(paramType, result)) {
        throw new IllegalStateException(
                "Standard argument type [" + paramType.getName() + "] in method " + parameter.getMethod() +
                "resolved to incompatible value of type [" + (result != null ? result.getClass() : null) +
                "]. Consider declaring the argument type in a less specific fashion.");
    }
    return result;
}
项目:bekit    文件:ProcessorParser.java   
/**
 * 解析处理器方法
 */
private static ProcessorMethodExecutor parseProcessorMethod(Class clazz, Method method) {
    logger.debug("解析处理器方法:{}", method);
    // 校验方法类型
    if (!Modifier.isPublic(method.getModifiers())) {
        throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型");
    }
    // 校验入参
    Class[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "入参必须是(TargetContext)");
    }
    if (parameterTypes[0] != TargetContext.class) {
        throw new IllegalArgumentException("处理器方法" + ClassUtils.getQualifiedMethodName(method) + "入参必须是(TargetContext)");
    }
    // 校验返回类型
    if (clazz != ProcessorExecute.class && method.getReturnType() != void.class) {
        throw new IllegalArgumentException("非@ProcessorExecute类型的处理器方法" + ClassUtils.getQualifiedMethodName(method) + "的返回类型必须是void");
    }
    // 获取目标对象类型
    ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0);
    Class classOfTarget = resolvableType.getGeneric(0).resolve(Object.class);

    return new ProcessorMethodExecutor(method, classOfTarget);
}
项目:lams    文件:NameMatchTransactionAttributeSource.java   
@Override
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
    if (!ClassUtils.isUserLevelMethod(method)) {
        return null;
    }

    // Look for direct name match.
    String methodName = method.getName();
    TransactionAttribute attr = this.nameMap.get(methodName);

    if (attr == null) {
        // Look for most specific name match.
        String bestNameMatch = null;
        for (String mappedName : this.nameMap.keySet()) {
            if (isMatch(methodName, mappedName) &&
                    (bestNameMatch == null || bestNameMatch.length() <= mappedName.length())) {
                attr = this.nameMap.get(mappedName);
                bestNameMatch = mappedName;
            }
        }
    }

    return attr;
}
项目:lams    文件:AutowireUtils.java   
/**
 * Determine whether the given bean property is excluded from dependency checks.
 * <p>This implementation excludes properties defined by CGLIB.
 * @param pd the PropertyDescriptor of the bean property
 * @return whether the bean property is excluded
 */
public static boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) {
    Method wm = pd.getWriteMethod();
    if (wm == null) {
        return false;
    }
    if (!wm.getDeclaringClass().getName().contains("$$")) {
        // Not a CGLIB method so it's OK.
        return false;
    }
    // It was declared by CGLIB, but we might still want to autowire it
    // if it was actually declared by the superclass.
    Class<?> superclass = wm.getDeclaringClass().getSuperclass();
    return !ClassUtils.hasMethod(superclass, wm.getName(), wm.getParameterTypes());
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:WebDriverAutoConfigurationTests.java   
@Test
public void testWithMockedChrome() {
    load(new Class[]{},
        "com.greglturnquist.webdriver.firefox.enabled:false",
        "com.greglturnquist.webdriver.safari.enabled:false");
    WebDriver driver = context.getBean(WebDriver.class);
    assertThat(ClassUtils.isAssignable(TakesScreenshot.class,
        driver.getClass())).isTrue();
    assertThat(ClassUtils.isAssignable(ChromeDriver.class,
        driver.getClass())).isTrue();
}
项目:lams    文件:RemoteInvocationTraceInterceptor.java   
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    if (logger.isDebugEnabled()) {
        logger.debug("Incoming " + this.exporterNameClause + "remote call: " +
                ClassUtils.getQualifiedMethodName(method));
    }
    try {
        Object retVal = invocation.proceed();
        if (logger.isDebugEnabled()) {
            logger.debug("Finished processing of " + this.exporterNameClause + "remote call: " +
                    ClassUtils.getQualifiedMethodName(method));
        }
        return retVal;
    }
    catch (Throwable ex) {
        if (ex instanceof RuntimeException || ex instanceof Error) {
            if (logger.isWarnEnabled()) {
                logger.warn("Processing of " + this.exporterNameClause + "remote call resulted in fatal exception: " +
                        ClassUtils.getQualifiedMethodName(method), ex);
            }
        }
        else {
            if (logger.isInfoEnabled()) {
                logger.info("Processing of " + this.exporterNameClause + "remote call resulted in exception: " +
                        ClassUtils.getQualifiedMethodName(method), ex);
            }
        }
        throw ex;
    }
}
项目:lams    文件:ClassArrayEditor.java   
@Override
public void setAsText(String text) throws IllegalArgumentException {
    if (StringUtils.hasText(text)) {
        String[] classNames = StringUtils.commaDelimitedListToStringArray(text);
        Class<?>[] classes = new Class<?>[classNames.length];
        for (int i = 0; i < classNames.length; i++) {
            String className = classNames[i].trim();
            classes[i] = ClassUtils.resolveClassName(className, this.classLoader);
        }
        setValue(classes);
    }
    else {
        setValue(null);
    }
}
项目:incubator-servicecomb-java-chassis    文件:JavassistUtils.java   
public static String getNameForGenerateCode(JavaType javaType) {
  if (byte[].class.equals(javaType.getRawClass())) {
    return "byte[]";
  }

  if (!javaType.isArrayType()) {
    Class<?> rawClass = ClassUtils.resolvePrimitiveIfNecessary(javaType.getRawClass());
    return rawClass.getTypeName();
  }

  return javaType.getContentType().getRawClass().getName() + "[]";
}
项目:incubator-servicecomb-java-chassis    文件:ProtobufSchemaUtils.java   
private static boolean isNeedWrap(Class<?> cls) {
  // protobuf不支持原子类型、enum、string、数组、collection等等作为msg
  // 只有pojo类型才可以
  // java.lang.Object也不可以,因为这可以是任意类型,结果不确定
  return ClassUtils.isPrimitiveOrWrapper(cls) || cls.isArray() || cls.isEnum()
      || String.class.isAssignableFrom(cls)
      || Collection.class.isAssignableFrom(cls)
      || Map.class.isAssignableFrom(cls)
      || Date.class.isAssignableFrom(cls)
      || Object.class.equals(cls);
}
项目:mybatis-plus-mini    文件:PackageHelper.java   
/**
   * <p>
   * 别名通配符设置
   * </p>
   * <p>
   * <property name="typeAliasesPackage" value="com.baomidou.*.entity"/>
   * </p>
   *
   * @param typeAliasesPackage 类别名包路径
   * @return
   */
  public static String[] convertTypeAliasesPackage(String typeAliasesPackage) {
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
      String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
              + ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/*.class";

/*
       * 将加载多个绝对匹配的所有Resource
 * 将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分,然后进行遍历模式匹配,排除重复包路径
 */
      try {
          Set<String> set = new HashSet<>();
          Resource[] resources = resolver.getResources(pkg);
          if (resources != null && resources.length > 0) {
              MetadataReader metadataReader;
              for (Resource resource : resources) {
                  if (resource.isReadable()) {
                      metadataReader = metadataReaderFactory.getMetadataReader(resource);
                      set.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                  }
              }
          }
          if (!set.isEmpty()) {
              return set.toArray(new String[]{});
          } else {
              throw new MybatisPlusException("not find typeAliasesPackage:" + pkg);
          }
      } catch (Exception e) {
          throw new MybatisPlusException("not find typeAliasesPackage:" + pkg, e);
      }
  }
项目:framework    文件:ThriftUtil.java   
public static TProcessor buildProcessor(Class<?> svcInterface, Object service) throws Exception {
    Class<TProcessor> processorClass = (Class<TProcessor>) getThriftServiceInnerClassOrNull(svcInterface.getEnclosingClass(), PROCESSOR_NAME, false);
    if (processorClass == null) {
        throw new ThriftRuntimeException("the processor is null");
    }

    Constructor<TProcessor> constructor = ClassUtils.getConstructorIfAvailable(processorClass, svcInterface);
    if (constructor == null) {
        throw new ThriftRuntimeException("the processor constructor is null");
    }

    return constructor.newInstance(service);
}
项目:bekit    文件:ListenerHolder.java   
/**
 * 获取指定类型的监听器执行器
 *
 * @param type 监听器类型
 * @throws IllegalArgumentException 如果不存在该类型的监听器执行器
 */
public List<ListenerExecutor> getRequiredListenerExecutors(Class type) {
    if (!listenerExecutorsMap.containsKey(type)) {
        throw new IllegalArgumentException("不存在" + ClassUtils.getShortName(type) + "类型的监听器");
    }
    return listenerExecutorsMap.get(type);
}
项目:bekit    文件:ServiceExecutor.java   
/**
 * 设置服务阶段执行器
 *
 * @param clazz         服务阶段注解的class
 * @param phaseExecutor 服务阶段执行器
 * @throws IllegalArgumentException 如果入参class不是服务阶段注解
 * @throws IllegalStateException    如果已存在该类型的服务阶段执行器
 */
public void setPhaseExecutor(Class clazz, ServicePhaseExecutor phaseExecutor) {
    if (!Arrays.asList(SERVICE_PHASE_ANNOTATIONS).contains(clazz)) {
        throw new IllegalArgumentException(ClassUtils.getShortName(clazz) + "不是服务阶段注解");
    }
    if (phaseExecutorMap.containsKey(clazz)) {
        throw new IllegalStateException("服务" + serviceName + "存在多个@" + ClassUtils.getShortName(clazz) + "类型方法");
    }
    phaseExecutorMap.put(clazz, phaseExecutor);
}
项目:lams    文件:TypeMismatchException.java   
/**
 * Create a new TypeMismatchException without PropertyChangeEvent.
 * @param value the offending value that couldn't be converted (may be {@code null})
 * @param requiredType the required target type (or {@code null} if not known)
 * @param cause the root cause (may be {@code null})
 */
public TypeMismatchException(Object value, Class<?> requiredType, Throwable cause) {
    super("Failed to convert value of type '" + ClassUtils.getDescriptiveType(value) + "'" +
            (requiredType != null ? " to required type '" + ClassUtils.getQualifiedName(requiredType) + "'" : ""),
            cause);
    this.value = value;
    this.requiredType = requiredType;
}