Example usage for java.lang ClassLoader getClass

List of usage examples for java.lang ClassLoader getClass

Introduction

In this page you can find the example usage for java.lang ClassLoader getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.pepstock.jem.node.tasks.jndi.AbsoluteHashMap.java

/**
 * This is a singleton. If instance is not null, means that local map is already loaded.
 * If null and classload is ANT classloader, then uses the proxy to load the instance from parent classloader, 
 * otherwise it creates a new instance./*  w  w w  . j  a v  a 2s.  co m*/
 * @return shared HashMap.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
static synchronized Map<String, Object> getInstance() {
    ClassLoader myClassLoader = AbsoluteHashMap.class.getClassLoader();
    if (instance == null) {
        // The root classloader is sun.misc.Launcher package. If we are not in a sun package,
        // we need to get hold of the instance of ourself from the class in the root classloader.
        // checks is ANT classloader
        if (myClassLoader.getClass().getName().startsWith("org.apache.tools.ant.loader.AntClassLoader")
                || myClassLoader.getClass().getName().startsWith(ReverseURLClassLoader.class.getName())) {
            try {
                // So we find our parent classloader
                ClassLoader parentClassLoader = myClassLoader.getParent();
                // And get the other version of our current class
                Class otherClassInstance = parentClassLoader.loadClass(AbsoluteHashMap.class.getName());
                // And call its getInstance method - this gives the correct instance of ourself
                Method getInstanceMethod = otherClassInstance.getDeclaredMethod("getInstance",
                        new Class[] { String.class });
                String internalKey = createKey();
                Object otherAbsoluteSingleton = getInstanceMethod.invoke(null, new Object[] { internalKey });
                // But, we can't cast it to our own interface directly because classes loaded from
                // different classloaders implement different versions of an interface.
                // So instead, we use java.lang.reflect.Proxy to wrap it in an object that
                // supports our interface, and the proxy will use reflection to pass through all calls
                // to the object.
                instance = (Map<String, Object>) Proxy.newProxyInstance(myClassLoader,
                        new Class[] { Map.class }, new DelegateInvocationHandler(otherAbsoluteSingleton));
            } catch (SecurityException e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            } catch (IllegalArgumentException e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            } catch (ClassNotFoundException e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            } catch (NoSuchMethodException e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            } catch (IOException e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
            // We're in the root classloader, so the instance we have here is the correct one
        } else {
            instance = new AbsoluteHashMap();
        }
    }
    return instance;
}

From source file:org.shelloid.netverif.test.suite.VerificationTestCase.java

private boolean fromSuite() {
    final String cl = this.getClass().getClassLoader().getClass().getName();
    ClassLoader loader = this.getClass().getClassLoader();
    int i = 0;//from w ww. j ava  2 s .  com
    while (loader != null && i < 10) {
        System.out.println("Loader: " + loader.getClass().getName());
        loader = loader.getParent();
    }
    return cl.contains("ClassTransformerClassLoader");
}

From source file:org.shelloid.netverif.TestRunnable.java

public TestRunnable() {
    ClassLoader loader = this.getClass().getClassLoader();
    int i = 0;/*w w w . j  a  va  2  s.  c o  m*/
    while (loader != null && i < 10) {
        System.out.println("Loader: " + loader.getClass().getName());
        loader = loader.getParent();
    }

}

From source file:org.springframework.context.weaving.DefaultContextLoadTimeWeaver.java

@Nullable
protected LoadTimeWeaver createServerSpecificLoadTimeWeaver(ClassLoader classLoader) {
    String name = classLoader.getClass().getName();
    try {//from   www .  j  av  a  2  s .  com
        if (name.startsWith("org.apache.catalina")) {
            return new TomcatLoadTimeWeaver(classLoader);
        } else if (name.startsWith("org.glassfish")) {
            return new GlassFishLoadTimeWeaver(classLoader);
        } else if (name.startsWith("org.jboss.modules")) {
            return new JBossLoadTimeWeaver(classLoader);
        } else if (name.startsWith("com.ibm.ws.classloader")) {
            return new WebSphereLoadTimeWeaver(classLoader);
        } else if (name.startsWith("weblogic")) {
            return new WebLogicLoadTimeWeaver(classLoader);
        }
    } catch (Exception ex) {
        if (logger.isInfoEnabled()) {
            logger.info("Could not obtain server-specific LoadTimeWeaver: " + ex.getMessage());
        }
    }
    return null;
}

From source file:org.springframework.instrument.classloading.InstrumentableClassLoaderFactoryBean.java

public void afterPropertiesSet() {
    if (!StringUtils.hasText(this.className)) {
        throw new IllegalArgumentException("className is required");
    }/*from w w w .jav  a  2  s .  co  m*/

    ClassLoader loader = ClassUtils.getDefaultClassLoader();

    // parse class loading hierarchy
    for (Class clazz = loader.getClass(); loader != null
            && this.classLoader == null; loader = loader.getParent()) {
        // check class itself
        if (analyzeClasses(loader, clazz)) {
            return;
        }
        // check interfaces
        if (analyzeClasses(loader, clazz.getInterfaces())) {
            return;
        }
        // check superclasses
        for (Class superClass = clazz.getSuperclass(); superClass != Object.class
                && superClass != null; superClass = clazz.getSuperclass())
            if (analyzeClasses(loader, superClass)) {
                return;
            }
    }

    throw new IllegalArgumentException(this.className + " was not found in the current classloader hierarchy - "
            + "see docs on how to use instrumented classloaders inside various environments");
}

From source file:org.springframework.instrument.classloading.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
 *///from w ww.ja va2s . c om
public ReflectiveLoadTimeWeaver(@Nullable ClassLoader classLoader) {
    Assert.notNull(classLoader, "ClassLoader must not be null");
    this.classLoader = classLoader;

    Method addTransformerMethod = ClassUtils.getMethodIfAvailable(this.classLoader.getClass(),
            ADD_TRANSFORMER_METHOD_NAME, ClassFileTransformer.class);
    if (addTransformerMethod == null) {
        throw new IllegalStateException("ClassLoader [" + classLoader.getClass().getName()
                + "] does NOT provide an " + "'addTransformer(ClassFileTransformer)' method.");
    }
    this.addTransformerMethod = addTransformerMethod;

    Method getThrowawayClassLoaderMethod = ClassUtils.getMethodIfAvailable(this.classLoader.getClass(),
            GET_THROWAWAY_CLASS_LOADER_METHOD_NAME);
    // getThrowawayClassLoader method is optional
    if (getThrowawayClassLoaderMethod == null) {
        if (logger.isInfoEnabled()) {
            logger.info("The ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide a "
                    + "'getThrowawayClassLoader()' method; SimpleThrowawayClassLoader will be used instead.");
        }
    }
    this.getThrowawayClassLoaderMethod = getThrowawayClassLoaderMethod;
}

From source file:org.squidy.common.dynamiccode.DynamicCodeClassLoader.java

/**
 * Extracts a classpath string from a given class loader. Recognizes only URLClassLoader.
 *//*w  w w.  j  a va  2  s .  c om*/
private static String extractClasspath(ClassLoader cl) {
    StringBuffer buf = new StringBuffer();

    while (cl != null) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("Trying to extract classpath of class loader: " + cl.getClass().getName());
        }

        if (cl instanceof URLClassLoader) {
            URL urls[] = ((URLClassLoader) cl).getURLs();
            for (int i = 0; i < urls.length; i++) {
                if (buf.length() > 0) {
                    buf.append(File.pathSeparatorChar);
                }

                String path = urls[i].getFile();
                if (path.startsWith("/C:/") || path.startsWith("/c:/")) {
                    path = path.substring(1, path.length());
                    path = path.replace('/', '\\');
                    path = path.replace("%20", " ");
                }
                buf.append(path);
            }
        }
        cl = cl.getParent();
    }

    return buf.toString();
}