Example usage for java.lang Class getClassLoader

List of usage examples for java.lang Class getClassLoader

Introduction

In this page you can find the example usage for java.lang Class getClassLoader.

Prototype

@CallerSensitive
@ForceInline 
public ClassLoader getClassLoader() 

Source Link

Document

Returns the class loader for the class.

Usage

From source file:org.bytesoft.bytejta.supports.spring.ManagedConnectionFactoryPostProcessor.java

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

    Class<?> clazz = bean.getClass();
    ClassLoader cl = clazz.getClassLoader();

    Class<?>[] interfaces = clazz.getInterfaces();

    if (XADataSource.class.isInstance(bean)) {
        ManagedConnectionFactoryHandler interceptor = new ManagedConnectionFactoryHandler(bean);
        interceptor.setIdentifier(beanName);
        return Proxy.newProxyInstance(cl, interfaces, interceptor);
    } else if (XAConnectionFactory.class.isInstance(bean)) {
        ManagedConnectionFactoryHandler interceptor = new ManagedConnectionFactoryHandler(bean);
        interceptor.setIdentifier(beanName);
        return Proxy.newProxyInstance(cl, interfaces, interceptor);
    } else if (ManagedConnectionFactory.class.isInstance(bean)) {
        ManagedConnectionFactoryHandler interceptor = new ManagedConnectionFactoryHandler(bean);
        interceptor.setIdentifier(beanName);
        return Proxy.newProxyInstance(cl, interfaces, interceptor);
    } else {//  w  ww .java2 s . c om
        return bean;
    }
}

From source file:org.hopen.framework.rewrite.CachedIntrospectionResults.java

/**
 * Create CachedIntrospectionResults for the given bean class.
 * <P>We don't want to use synchronization here. Object references are atomic,
 * so we can live with doing the occasional unnecessary lookup at startup only.
 * @param beanClass the bean class to analyze
 * @return the corresponding CachedIntrospectionResults
 * @throws BeansException in case of introspection failure
 *//*  w w w. ja  v  a  2s . c o  m*/
static CachedIntrospectionResults forClass(Class beanClass) throws BeansException {
    CachedIntrospectionResults results;
    Object value = classCache.get(beanClass);
    if (value instanceof Reference) {
        Reference ref = (Reference) value;
        results = (CachedIntrospectionResults) ref.get();
    } else {
        results = (CachedIntrospectionResults) value;
    }
    if (results == null) {
        // On JDK 1.5 and higher, it is almost always safe to cache the bean class...
        // The sole exception is a custom BeanInfo class being provided in a non-safe ClassLoader.
        boolean fullyCacheable = ClassUtils.isCacheSafe(beanClass,
                CachedIntrospectionResults.class.getClassLoader())
                || isClassLoaderAccepted(beanClass.getClassLoader());
        if (fullyCacheable
                || !ClassUtils.isPresent(beanClass.getName() + "BeanInfo", beanClass.getClassLoader())) {
            results = new CachedIntrospectionResults(beanClass, fullyCacheable);
            classCache.put(beanClass, results);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Not strongly caching class [" + beanClass.getName()
                        + "] because it is not cache-safe");
            }
            results = new CachedIntrospectionResults(beanClass, true);
            classCache.put(beanClass, new WeakReference<CachedIntrospectionResults>(results));
        }
    }
    return results;
}

From source file:ca.oson.json.util.ObjectUtil.java

/**
 * Returns a list containing one parameter name for each argument accepted
 * by the given constructor. If the class was compiled with debugging
 * symbols, the parameter names will match those provided in the Java source
 * code. Otherwise, a generic "arg" parameter name is generated ("arg0" for
 * the first argument, "arg1" for the second...).
 *
 * This method relies on the constructor's class loader to locate the
 * bytecode resource that defined its class.
 *
 * @param constructor the constructor to get a list of parameter names
 * @return a list of parameter names//from   w  w w  . ja  va  2  s . co m
 * @throws IOException io exception to throw
 */
private static List<String> getParameterNamesBytecode(Constructor<?> constructor) throws IOException {
    Class<?> declaringClass = constructor.getDeclaringClass();
    ClassLoader declaringClassLoader = declaringClass.getClassLoader();

    if (declaringClassLoader == null) {
        return null;
    }

    org.objectweb.asm.Type declaringType = org.objectweb.asm.Type.getType(declaringClass);
    String constructorDescriptor = org.objectweb.asm.Type.getConstructorDescriptor(constructor);
    String url = declaringType.getInternalName() + ".class";

    InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url);
    if (classFileInputStream == null) {
        // throw new IllegalArgumentException("The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: " + url + ")");
        return null;
    }

    ClassNode classNode;
    try {
        classNode = new ClassNode();
        ClassReader classReader = new ClassReader(classFileInputStream);
        classReader.accept(classNode, 0);
    } finally {
        classFileInputStream.close();
    }

    @SuppressWarnings("unchecked")
    List<MethodNode> methods = classNode.methods;
    for (MethodNode method : methods) {
        if (method.name.equals("<init>") && method.desc.equals(constructorDescriptor)) {
            org.objectweb.asm.Type[] argumentTypes = org.objectweb.asm.Type.getArgumentTypes(method.desc);
            List<String> parameterNames = new ArrayList<String>(argumentTypes.length);

            @SuppressWarnings("unchecked")
            List<LocalVariableNode> localVariables = method.localVariables;
            for (int i = 0; i < argumentTypes.length && i < localVariables.size() - 1; i++) {
                // The first local variable actually represents the "this" object
                parameterNames.add(localVariables.get(i + 1).name);
            }

            return parameterNames;
        }
    }

    return null;
}

From source file:grails.util.GrailsClassUtils.java

public static FastClass fastClass(Class superClass) {
    FastClass.Generator gen = new FastClass.Generator();
    gen.setType(superClass);//from   www  .  j av a 2 s  .c  o m
    gen.setClassLoader(superClass.getClassLoader());
    gen.setUseCache(!Environment.isReloadingAgentEnabled());
    return gen.create();
}

From source file:Classes.java

/**
 * Instantiate a java class object//w  ww .  java 2s .co  m
 * 
 * @param expected
 *          the expected class type
 * @param property
 *          the system property defining the class
 * @param defaultClassName
 *          the default class name
 * @return the instantiated object
 */
public static Object instantiate(Class expected, String property, String defaultClassName) {
    String className = getProperty(property, defaultClassName);
    Class clazz = null;
    try {
        clazz = loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Cannot load class " + className, e);
    }
    Object result = null;
    try {
        result = clazz.newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException("Error instantiating " + className, e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Error instantiating " + className, e);
    }
    if (expected.isAssignableFrom(clazz) == false)
        throw new RuntimeException("Class " + className + " from classloader " + clazz.getClassLoader()
                + " is not of the expected class " + expected + " loaded from " + expected.getClassLoader());
    return result;
}

From source file:org.force66.beantester.utils.GenericProxyHandlerTest.java

private Object makeProxy(Class<?> interfaceType) {
    return Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class[] { interfaceType },
            new GenericProxyHandler(interfaceType));
}

From source file:org.eclipse.emf.teneo.classloader.ClassClassLoaderStrategy.java

/**
 * Just returns the classClassLoader//from   w w w  . jav  a  2 s .  co m
 */
public ClassLoader getClassLoader() {
    /*
     * 0: SecurityManager.getClassContext 1: getClassContext 2: getCallerClass 3: getClassLoader
     * 4: ClassLoaderResolver.getClassLoader 5: app class
     */
    final Class<?> clazz = getCallerClass(5);
    return clazz.getClassLoader();
}

From source file:jenkins.scm.api.SCMHeadMixinEqualityGenerator.java

/**
 * Get the {@link SCMHeadMixin.Equality} instance to use.
 *
 * @param type the {@link SCMHead} type.
 * @return the {@link SCMHeadMixin.Equality} instance.
 *//*from  ww w .  ja  v a 2s . c  om*/
@NonNull
static SCMHeadMixin.Equality getOrCreate(@NonNull Class<? extends SCMHead> type) {
    lock.readLock().lock();
    try {
        SCMHeadMixin.Equality result = mixinEqualities.get(type);
        if (result != null) {
            return result;
        }
    } finally {
        lock.readLock().unlock();
    }
    lock.writeLock().lock();
    try {
        SCMHeadMixin.Equality result = mixinEqualities.get(type);
        if (result != null) {
            // somebody else created it while we were waiting for the write lock
            return result;
        }
        final ClassLoader loader = type.getClassLoader();
        SCMHeadMixinEqualityGenerator generator;
        generator = generators.get(loader);
        if (generator == null) {
            generator = AccessController.doPrivileged(new PrivilegedAction<SCMHeadMixinEqualityGenerator>() {
                @Override
                public SCMHeadMixinEqualityGenerator run() {
                    return new SCMHeadMixinEqualityGenerator(loader);
                }
            });
            generators.put(loader, generator);
        }
        result = generator.create(type);
        mixinEqualities.put(type, result);
        return result;
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.apache.giraph.graph.GraphTaskManager.java

/**
 * Copied from JobConf to get the location of this jar.  Workaround for
 * things like Oozie map-reduce jobs. NOTE: Pure YARN profile cannot
 * make use of this, as the jars are unpacked at each container site.
 *
 * @param myClass Class to search the class loader path for to locate
 *        the relevant jar file/* www.ja v  a  2 s .c om*/
 * @return Location of the jar file containing myClass
 */
private static String findContainingJar(Class<?> myClass) {
    ClassLoader loader = myClass.getClassLoader();
    String classFile = myClass.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<?> itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.gradle.model.internal.manage.state.ManagedModelElementInstanceFactory.java

public <T> T create(ManagedModelElement<T> element) {
    Class<T> type = element.getType();
    Object instance = Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type },
            new ManagedModelElementInvocationHandler(element, store));
    store.add(instance);/*from   ww  w .  jav a  2s  .c om*/
    @SuppressWarnings("unchecked")
    T typedInstance = (T) instance;
    return typedInstance;
}