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:Main.java

public static void main(String[] args) throws Exception {
    Class cls = Class.forName("java.lang.String");
    // returns the ClassLoader object associated with this Class.
    ClassLoader cLoader = cls.getClassLoader();

    if (cLoader == null) {
        System.out.println("The default system class was used.");
    } else {/*from ww w . ja  v  a  2 s .co  m*/
        // returns the class loader
        Class loaderClass = cLoader.getClass();
        System.out.println(loaderClass.getName());
    }
}

From source file:Main.java

public static String findJniLibrary(Context context, String libName) {
    String result = null;/*ww  w  .ja  va 2  s.co  m*/
    ClassLoader classLoader = (context.getClassLoader());
    if (classLoader != null) {
        try {
            Method findLibraryMethod = classLoader.getClass().getMethod("findLibrary",
                    new Class<?>[] { String.class });
            if (findLibraryMethod != null) {
                Object objPath = findLibraryMethod.invoke(classLoader, new Object[] { libName });
                if (objPath != null && objPath instanceof String) {
                    result = (String) objPath;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    return result;
}

From source file:Main.java

/**
 * Use reflection to access a URL[] getURLs or URL[] getClasspath method so
 * that non-URLClassLoader class loaders, or class loaders that override
 * getURLs to return null or empty, can provide the true classpath info.
 * //from   w  ww  .  j  a  va2  s  .  c o  m
 * @param cl
 * @return the urls
 */
public static URL[] getClassLoaderURLs(ClassLoader cl) {
    URL[] urls = {};
    try {
        Class returnType = urls.getClass();
        Class[] parameterTypes = {};
        Class clClass = cl.getClass();
        Method getURLs = clClass.getMethod("getURLs", parameterTypes);
        if (returnType.isAssignableFrom(getURLs.getReturnType())) {
            Object[] args = {};
            urls = (URL[]) getURLs.invoke(cl, args);
        }
        if (urls == null || urls.length == 0) {
            Method getCp = clClass.getMethod("getClasspath", parameterTypes);
            if (returnType.isAssignableFrom(getCp.getReturnType())) {
                Object[] args = {};
                urls = (URL[]) getCp.invoke(cl, args);
            }
        }
    } catch (Exception ignore) {
    }
    return urls;
}

From source file:com.npower.dm.util.DMUtil.java

/**
 * Use reflection to access a URL[] getURLs or ULR[] getAllURLs method so that
 * non-URLClassLoader class loaders, or class loaders that override getURLs to
 * return null or empty, can provide the true classpath info.
 *///w w w  .j a  va2  s  .  c o m
public static URL[] getClassLoaderURLs(ClassLoader cl) {
    URL[] urls = {};
    try {
        Class<?> returnType = urls.getClass();
        Class<?>[] parameterTypes = {};
        Method getURLs = cl.getClass().getMethod("getURLs", parameterTypes);
        if (returnType.isAssignableFrom(getURLs.getReturnType())) {
            Object[] args = {};
            urls = (URL[]) getURLs.invoke(cl, args);
        }
    } catch (Exception ignore) {
    }
    return urls;
}

From source file:com.streamsets.pipeline.stage.destination.mapreduce.MapreduceUtils.java

/**
 * Add jars whose names contain the given patterns to the job's classpath.
 *
 * Searches the {@link ClassLoader} - which must be an instance of {@link URLClassLoader} or an
 * {@link IllegalStateException} will be thrown - of the {@link MapreduceUtils} class itself for the jar matching
 * a pattern indicated each arguments./*from  ww w .  java2 s . c  o  m*/
 *
 * Each supplied jarPattern is treated as a case-insensitive substring for a full jar path.  This method expects
 * to find at least one jar matching each substring, or an {@link IllegalArgumentException} will be thrown.  If more
 * than one jar is matched, then the result will depend on the allowMultiple parameter - if true, then all will be
 * added, while if false, an {@link IllegalArgumentException} will be thrown.
 *
 * Care has <b>NOT</b> been taken to optimize the performance of this method; the runtime is M * N where M is the
 * number of entries on the classpath and N is the number of given jarPatterns.  It is assumed that this method
 * will be called infrequently and with relatively few jarPatterns.
 *
 * @param conf the Hadoop conf for the MapReduce job
 * @param allowMultiple whether multiple matching jars are allowed to be added for a single pattern
 * @param jarPatterns the patterns to search for within the classpath
 */
public static void addJarsToJob(Configuration conf, boolean allowMultiple, String... jarPatterns) {
    final ClassLoader loader = MapreduceUtils.class.getClassLoader();
    if (!(loader instanceof URLClassLoader)) {
        throw new IllegalStateException(String.format(
                "ClassLoader for %s is not an instance of URLClassLoader (it is %s), and thus this method cannot be used",
                MapreduceUtils.class.getCanonicalName(), loader.getClass().getCanonicalName()));
    }
    final URLClassLoader urlClassLoader = (URLClassLoader) loader;

    addJarsToJob(conf, allowMultiple, urlClassLoader.getURLs(), jarPatterns);
}

From source file:com.feilong.core.lang.ClassLoaderUtil.java

/**
 * Format class loader./*from www .j av  a2s  .co m*/
 *
 * @param classLoader
 *            the class loader
 * @return the string
 * @since 1.6.2
 */
private static String formatClassLoader(ClassLoader classLoader) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("classLoader", "" + classLoader);
    map.put("classLoader[CanonicalName]", classLoader.getClass().getCanonicalName());
    map.put("classLoader[Root Classpath]", "" + getRootClassPath(classLoader));
    return JsonUtil.format(map);
}

From source file:com.sunchenbin.store.feilong.core.lang.ClassLoaderUtil.java

/**
 *  {@link ClassLoader} info map for LOGGER.
 *
 * @param classLoader/* w  w w .  j a v  a2 s. c  om*/
 *            the class loader
 * @return the class loader info map for log
 * @since 1.1.1
 */
private static Map<String, Object> getClassLoaderInfoMapForLog(ClassLoader classLoader) {
    Map<String, Object> classLoaderInfoMap = new LinkedHashMap<String, Object>();
    classLoaderInfoMap.put("classLoader", "" + classLoader);
    classLoaderInfoMap.put("classLoader[CanonicalName]", classLoader.getClass().getCanonicalName());
    classLoaderInfoMap.put("classLoader[Root Classpath]", "" + getClassPath(classLoader));
    return classLoaderInfoMap;
}

From source file:net.nifheim.beelzebu.coins.common.utils.dependencies.DependencyManager.java

private static void loadJar(File file) throws RuntimeException {
    // get the classloader to load into
    ClassLoader classLoader = core.getMethods().getPlugin().getClass().getClassLoader();

    if (classLoader instanceof URLClassLoader) {
        try {/*  w  w w . j  a va  2s  .com*/
            ADD_URL_METHOD.invoke(classLoader, file.toURI().toURL());
        } catch (IllegalAccessException | InvocationTargetException | MalformedURLException e) {
            throw new RuntimeException("Unable to invoke URLClassLoader#addURL", e);
        }
    } else {
        throw new RuntimeException("Unknown classloader type: " + classLoader.getClass());
    }
}

From source file:doc.doclets.WorkbenchHelpDoclet.java

/**
 * Process the java files and generate PtDoc XML. Only classes that extend ptolemy.actor.TypedAtomicActor are processed, all other classes are ignored.
 * //  w  w  w  . ja  v a  2s.c o  m
 * @param root The root of the java doc tree.
 * @return Always return true;
 * @exception IOException If there is a problem writing the documentation.
 * @exception ClassNotFoundException If there is a problem finding the class of one of the fields.
 */
public static boolean start(final RootDoc root) throws IOException, ClassNotFoundException {
    System.out.println("Isencia version of PtDoc, with Kepler extensions");

    Context velocityContext = new VelocityContext();

    final ClassLoader classLoader = WorkbenchHelpDoclet.class.getClassLoader();
    System.out.println("Using classloader " + classLoader.getClass());
    if (URLClassLoader.class.isInstance(classLoader)) {
        final URL[] classPathURLs = ((URLClassLoader) classLoader).getURLs();
        for (final URL url : classPathURLs) {
            System.out.println("\n classPathURL " + url);
        }
    }

    _outputDirectory = _getOutputDirectory(root.options());
    final File outputDirectoryFile = new File(_outputDirectory);
    if (!outputDirectoryFile.isDirectory()) {
        if (!outputDirectoryFile.mkdirs()) {
            throw new IOException("Failed to create \"" + _outputDirectory + "\"");
        }
    }

    final ClassDoc baseActorDoc = root.classNamed("com.isencia.passerelle.actor.Actor");

    final ClassDoc[] classes = root.classes();
    final Collection<ClassDoc> actorClasses = filterClasses(baseActorDoc, classes);

    generateActorHelpFiles(root, actorClasses);

    generateActorHelpIndex(root, actorClasses);
    generateActorHelpTOC(root, actorClasses);
    generateActorHelpHtmlTOC(root, actorClasses);

    return true;
}

From source file:azkaban.common.utils.Utils.java

public static List<String> getClassLoaderDescriptions(ClassLoader loader) {
    List<String> values = new ArrayList<String>();
    while (loader != null) {
        if (loader instanceof URLClassLoader) {
            URLClassLoader urlLoader = (URLClassLoader) loader;
            for (URL url : urlLoader.getURLs())
                values.add(url.toString());
        } else {/*from  w w  w  . ja  v a2 s  .c  o m*/
            values.add(loader.getClass().getName());
        }
        loader = loader.getParent();
    }
    return values;
}