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:net.lightbody.bmp.proxy.jetty.util.jmx.ModelMBeanImpl.java

/** Create MBean for Object.
 * Attempts to create an MBean for the object by searching the
 * package and class name space.  For example an object of the
 * type <PRE>//from  ww  w . j av a 2 s . c  o  m
 *   class com.acme.MyClass extends com.acme.util.BaseClass
 * </PRE>
 * Then this method would look for the following
 * classes:<UL>
 * <LI>com.acme.MyClassMBean
 * <LI>com.acme.jmx.MyClassMBean
 * <LI>com.acme.util.BaseClassMBean
 * <LI>com.acme.util.jmx.BaseClassMBean
 * </UL>
 * @param o The object
 * @return A new instance of an MBean for the object or null.
 */
public static ModelMBean mbeanFor(Object o) {
    try {
        Class oClass = o.getClass();
        ClassLoader loader = oClass.getClassLoader();

        ModelMBean mbean = null;
        boolean jmx = false;
        Class[] interfaces = null;
        int i = 0;

        while (mbean == null && oClass != null) {
            Class focus = interfaces == null ? oClass : interfaces[i];
            String pName = focus.getPackage().getName();
            String cName = focus.getName().substring(pName.length() + 1);
            String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean";

            try {
                Class mClass = loader.loadClass(mName);
                if (log.isTraceEnabled())
                    log.trace("mbeanFor " + o + " mClass=" + mClass);
                mbean = (ModelMBean) mClass.newInstance();
                mbean.setManagedResource(o, "objectReference");
                if (log.isDebugEnabled())
                    log.debug("mbeanFor " + o + " is " + mbean);
                return mbean;
            } catch (ClassNotFoundException e) {
                if (e.toString().endsWith("MBean")) {
                    if (log.isTraceEnabled())
                        log.trace(e.toString());
                } else
                    log.warn(LogSupport.EXCEPTION, e);
            } catch (Error e) {
                log.warn(LogSupport.EXCEPTION, e);
                mbean = null;
            } catch (Exception e) {
                log.warn(LogSupport.EXCEPTION, e);
                mbean = null;
            }

            if (jmx) {
                if (interfaces != null) {
                    i++;
                    if (i >= interfaces.length) {
                        interfaces = null;
                        oClass = oClass.getSuperclass();
                    }
                } else {
                    interfaces = oClass.getInterfaces();
                    i = 0;
                    if (interfaces == null || interfaces.length == 0) {
                        interfaces = null;
                        oClass = oClass.getSuperclass();
                    }
                }
            }
            jmx = !jmx;
        }
    } catch (Exception e) {
        LogSupport.ignore(log, e);
    }
    return null;
}

From source file:org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.java

/**
 * @param cls//w  ww .j  a va  2 s  . c  om
 * @return ClassLoader or null if cannot be obtained
 */
private static ClassLoader getClassLoader(final Class cls) {
    // NOTE: This method must remain private because it uses AccessController
    if (cls == null) {
        return null;
    }
    ClassLoader cl = null;
    try {
        cl = (ClassLoader) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                return cls.getClassLoader();
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e);
        }
    }

    return cl;
}

From source file:com.google.gdt.eclipse.designer.util.GwtInvocationEvaluatorInterceptor.java

/**
 * @return the <code>Widget</code> to use as placeholder instead of real component that can not be
 *         created because of some exception.
 *//*  w  w  w.j a v  a2  s  .  co  m*/
private static Object createPlaceholder(Class<?> clazz) throws Exception {
    String message = MessageFormat.format(
            "Exception during creation of: {0}. See \"Open error log\" for details.",
            CodeUtils.getShortClass(clazz.getName()));
    // script
    String script;
    {
        AstEditor editor = EditorState.getActiveJavaInfo().getEditor();
        ComponentDescription description = ComponentDescriptionHelper.getDescription(editor, clazz);
        script = description.getParameter("placeholderScript");
    }
    // variables
    Map<String, Object> variables = Maps.newTreeMap();
    variables.put("clazz", clazz);
    variables.put("message", message);
    // execute
    ClassLoader classLoader = clazz.getClassLoader();
    return ScriptUtils.evaluate(classLoader, script, variables);
}

From source file:org.codebistro.jsonrpc.Client.java

public <T> T openProxy(String tag, Class<T> klass) {
    Object result = java.lang.reflect.Proxy.newProxyInstance(klass.getClassLoader(), new Class[] { klass },
            this);
    proxyMap.put(result, tag);//from   w w w.j  a v  a2s  .  c  o  m
    return klass.cast(result);
}

From source file:com.laidians.utils.ClassUtils.java

/**
 * Check whether the given class is cache-safe in the given context,
 * i.e. whether it is loaded by the given ClassLoader or a parent of it.
 * @param clazz the class to analyze//from   w w w .ja  v a  2 s  . co  m
 * @param classLoader the ClassLoader to potentially cache metadata in
 */
public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
    Assert.notNull(clazz, "Class must not be null");
    ClassLoader target = clazz.getClassLoader();
    if (target == null) {
        return false;
    }
    ClassLoader cur = classLoader;
    if (cur == target) {
        return true;
    }
    while (cur != null) {
        cur = cur.getParent();
        if (cur == target) {
            return true;
        }
    }
    return false;
}

From source file:io.coala.json.DynaBean.java

/**
 * @param om the {@link ObjectMapper} for get and set de/serialization
 * @param type the type of {@link Proxy} to generate
 * @param bean the (prepared) {@link DynaBean} for proxied getters/setters
 * @param imports default value {@link Properties} of the bean
 * @return a {@link Proxy} instance backed by an empty {@link DynaBean}
 *//*www.ja v a  2  s .  c om*/
@SuppressWarnings("unchecked")
public static <T> T proxyOf(final ObjectMapper om, final Class<T> type, final DynaBean bean,
        final Properties... imports) {
    //      if( !type.isAnnotationPresent( BeanProxy.class ) )
    //         throw ExceptionFactory.createUnchecked( "{} is not a @{}", type,
    //               BeanProxy.class.getSimpleName() );

    return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type },
            new DynaBeanInvocationHandler(om, type, bean, imports));
}

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

public T createInstance() {
    Class<T> concreteType = type.getConcreteClass();
    Object instance = Proxy.newProxyInstance(concreteType.getClassLoader(),
            new Class<?>[] { concreteType, ManagedInstance.class }, new ManagedModelElementInvocationHandler());
    @SuppressWarnings("unchecked")
    T typedInstance = (T) instance;// w w  w  .  j  a v  a2s  .  co  m
    return typedInstance;
}

From source file:org.apache.xml.security.utils.ClassLoaderUtils.java

/**
 * Load a given resource. <p/> This method will try to load the resource
 * using the following methods (in order):
 * <ul>/* w  w  w.j av a2s  .  co  m*/
 * <li>From Thread.currentThread().getContextClassLoader()
 * <li>From ClassLoaderUtil.class.getClassLoader()
 * <li>callingClass.getClassLoader()
 * </ul>
 * 
 * @param resourceName The name of the resource to load
 * @param callingClass The Class object of the calling object
 */
public static URL getResource(String resourceName, Class<?> callingClass) {
    URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
    if (url == null && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        url = Thread.currentThread().getContextClassLoader().getResource(resourceName.substring(1));
    }

    ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
    if (cluClassloader == null) {
        cluClassloader = ClassLoader.getSystemClassLoader();
    }
    if (url == null) {
        url = cluClassloader.getResource(resourceName);
    }
    if (url == null && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        url = cluClassloader.getResource(resourceName.substring(1));
    }

    if (url == null) {
        ClassLoader cl = callingClass.getClassLoader();

        if (cl != null) {
            url = cl.getResource(resourceName);
        }
    }

    if (url == null) {
        url = callingClass.getResource(resourceName);
    }

    if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
        return getResource('/' + resourceName, callingClass);
    }

    return url;
}

From source file:com.genentech.struchk.oeStruchk.OEStruchk.java

public static URL getResourceURL(Class<?> cls, String name) {
    String path = cls.getName().replace('.', '/');
    path = path.subSequence(0, path.lastIndexOf('/') + 1) + name;
    return cls.getClassLoader().getResource(path);
}

From source file:org.apache.hama.ipc.RPC.java

/**
 * Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 *//*from   w  ww. ja va 2  s  .c  o  m*/
public static VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory,
        int rpcTimeout, RetryPolicy connectionRetryPolicy, boolean checkVersion) throws IOException {

    if (UserGroupInformation.isSecurityEnabled()) {
        SaslRpcServer.init(conf);
    }
    final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout,
            connectionRetryPolicy);
    VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, invoker);

    if (checkVersion) {
        checkVersion(protocol, clientVersion, proxy);
    }
    return proxy;
}