Example usage for java.lang ClassLoader loadClass

List of usage examples for java.lang ClassLoader loadClass

Introduction

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

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:hermes.renderers.RendererManager.java

public MessageRenderer createRenderer(ClassLoader classLoader, RendererConfig rConfig)
        throws InvocationTargetException, HermesException, InstantiationException, IllegalAccessException,
        ClassNotFoundException {//from   w w  w .j  ava  2 s . c om
    Thread.currentThread().setContextClassLoader(classLoader);
    MessageRenderer renderer = (MessageRenderer) classLoader.loadClass(rConfig.getClassName()).newInstance();
    MessageRenderer.Config rendererConfig = renderer.createConfig();

    if (rendererConfig != null) {
        Properties rendererProperties = HermesBrowser.getConfigDAO().getRendererProperties(rConfig);

        BeanUtils.populate(rendererConfig, rendererProperties);
    }

    renderer.setConfig(rendererConfig);

    return renderer;
}

From source file:org.jsonschema2pojo.integration.config.CustomAnnotatorIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void customAnnotatorIsAbleToAddCustomAnnotations()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "none", // turn off core annotations
                    "customAnnotator", DeprecatingAnnotator.class.getName()));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue()));
}

From source file:com.framgia.android.emulator.EmulatorDetector.java

private String getProp(Context context, String property) {
    try {/*from w w w  . java2  s . co m*/
        ClassLoader classLoader = context.getClassLoader();
        Class<?> systemProperties = classLoader.loadClass("android.os.SystemProperties");

        Method get = systemProperties.getMethod("get", String.class);

        Object[] params = new Object[1];
        params[0] = property;

        return (String) get.invoke(systemProperties, params);
    } catch (Exception exception) {
        // empty catch
    }
    return null;
}

From source file:io.swagger.inflector.config.Configuration.java

public Configuration exceptionMapper(String className) {
    Class<?> cls;//w  w  w.j  av  a2s  .c  o  m
    try {
        ClassLoader classLoader = Configuration.class.getClassLoader();
        cls = classLoader.loadClass(className);
        exceptionMappers.add(cls);
    } catch (ClassNotFoundException e) {
        LOGGER.error("unable to add exception mapper for `" + className + "`, " + e.getMessage());
    }
    return this;
}

From source file:org.atm.mvn.run.JavaBootstrap.java

/**
 * Attempt to resolve the class from the class name specified.
 * /* w ww  . j  a  v  a2 s. c  o m*/
 * @param bootstrapClassLoader
 *            The class loader to use to load the class.
 * @return The {@link Class} instance
 * @throws RuntimeException
 *             if the class cannot be resolved.
 */
protected Class<?> resolveClass(ClassLoader bootstrapClassLoader) {
    // try resolving just the fully qualified class name
    try {
        Class<?> loadedClass = bootstrapClassLoader.loadClass(className);

        log.debug("Resolved fully qualified class name: " + className);

        return loadedClass;
    } catch (ClassNotFoundException e) {
    }

    PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(
            bootstrapClassLoader);

    // look for class files for the simple class name
    String locationPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "**/" + className + ".class";

    Resource[] resources;
    try {
        // run the search with spring
        // TODO might be possible to do this without a spring dependency
        resources = resourceResolver.getResources(locationPattern);

        log.debug("Found resources matching class name pattern: " + locationPattern);
        for (Resource resource : resources) {
            log.debug("  " + resource);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (resources.length > 0) {
        // assume that the first resource found is the one we want.
        Resource resource = resources[0];

        try {
            String url = resource.getURL().toString();

            log.debug("Attempting to resolve class name from URL: " + url);

            int jarMarkerIndex = url.indexOf('!');
            if (jarMarkerIndex != -1) {
                /* 
                 * This is not a jar based class file, so the proper fully
                 * qualified class name is not clear since the URL may 
                 * contain path segments that are not part of the package 
                 */
                String classUrl = url.toString();
                int pathStartIndex = classUrl.indexOf(":/") + 2;
                String classFilePath = classUrl.substring(pathStartIndex);

                /* 
                 * begin with the path minus .class and converted to fully 
                 * qualified class name format.
                 */
                String currentClassName = classFilePath
                        // remove the file extension
                        .substring(0, classFilePath.indexOf(".class"))
                        // convert the path separators to package separators
                        .replace('/', '.');

                // search for the class
                while (StringUtils.isNotEmpty(currentClassName)) {
                    // try loading the current class name
                    try {
                        Class<?> loadedClass = bootstrapClassLoader.loadClass(currentClassName);

                        log.debug(MessageFormat.format(
                                "Resolved class {0} " + "from URL {1} " + "for specified class name {1}.",
                                currentClassName, url, className));

                        return loadedClass;
                    } catch (ClassNotFoundException e) {
                        // class not found, so substring the path if possible
                        int nextPackageSeparatorIndex = currentClassName.indexOf('.');
                        if (nextPackageSeparatorIndex == -1) {
                            // nothing more to try
                            throw new RuntimeException("Unable to load class from class file " + classUrl, e);
                        } else {
                            // the next child path
                            currentClassName = currentClassName.substring(nextPackageSeparatorIndex + 1);
                        }
                    }
                }
            } else {
                /* 
                 * this is a resource contained in a JAR file, the pattern is:
                 * jar://path/to/jarFile.jar!/fully/qualified/ClassName.class
                 */
                String className = url.substring(jarMarkerIndex + 2, url.indexOf(".class")).replace('/', '.');

                try {
                    Class<?> loadedClass = bootstrapClassLoader.loadClass(className);

                    log.debug(MessageFormat.format(
                            "Resolved class {0} " + "from URL {1} " + "for specified class name {1}.",
                            className, url, this.className));

                    return loadedClass;
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("Unable to load class from resource: " + url, e);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Unable to convert resource URL to String: " + resource, e);
        }
    }

    throw new RuntimeException("Unable to resolve class for class name specified: " + className);
}

From source file:io.swagger.inflector.config.Configuration.java

public void setModelMappings(Map<String, String> mappings) {
    for (String key : mappings.keySet()) {
        String className = mappings.get(key);
        Class<?> cls;//from w  w  w . jav a 2s  .co  m
        try {
            ClassLoader classLoader = Configuration.class.getClassLoader();
            cls = classLoader.loadClass(className);
            modelMap.put(key, cls);
        } catch (ClassNotFoundException e) {
            unimplementedModels.add(className);
            LOGGER.error("unable to add mapping for `" + key + "` : `" + className + "`, " + e.getMessage());
        }
    }
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private void loadConfigurationClasses(final SpringApplicationService config) throws ClassNotFoundException {
    final ConfigurationClasses configurationClasses = config.getConfigurationClasses();
    if (configurationClasses != null && !CollectionUtils.isEmpty(configurationClasses.getClazz())) {
        final ClassLoader cl = getClass().getClassLoader();
        final List<Class<?>> configClasses = new ArrayList<>(configurationClasses.getClazz().size());
        for (final String clazz : configurationClasses.getClazz()) {
            final Class<?> c = cl.loadClass(clazz.trim());
            if (c.getAnnotation(Configuration.class) == null) {
                throw new IllegalArgumentException(String.format(
                        "Class must be annotated with @org.springframework.context.annotation.Configuration: {}",
                        clazz));/*from   ww  w  .j av a2  s  . co  m*/
            }
            configClasses.add(c);
        }
        this.configurationClasses = configClasses.toArray(new Class<?>[configClasses.size()]);
    }

}

From source file:com.google.gdt.eclipse.designer.uibinder.model.widgets.UIObjectInfo.java

/**
 * Call enter() as if this UI was create as result of call from JavaScript.
 *//* w  w  w.  j  av a  2s  .c  om*/
private void call_Impl_enter() {
    if (isRoot()) {
        ExecutionUtils.runIgnore(new RunnableEx() {
            public void run() throws Exception {
                ClassLoader classLoader = getContext().getClassLoader();
                Class<?> class_Impl = classLoader.loadClass("com.google.gwt.core.client.impl.Impl");
                ReflectionUtils.invokeMethod(class_Impl, "enter()");
            }
        });
    }
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.widgets.UIObjectInfo.java

/**
 * Call exit() as if this UI was create as result of call from JavaScript.
 *//*  ww w  .j a v  a 2 s . c  om*/
private void call_Impl_exit() {
    if (isRoot()) {
        ExecutionUtils.runIgnore(new RunnableEx() {
            public void run() throws Exception {
                ClassLoader classLoader = getContext().getClassLoader();
                Class<?> class_Impl = classLoader.loadClass("com.google.gwt.core.client.impl.Impl");
                ReflectionUtils.invokeMethod(class_Impl, "exit(boolean)", true);
            }
        });
    }
}

From source file:de.lmu.ifi.dbs.jfeaturelib.utils.PackageScanner.java

public List<Class<T>> scanForClass(Package thePackage, Class<T> needle)
        throws IOException, UnsupportedEncodingException, URISyntaxException {
    List<String> binaryNames = getNames(thePackage);
    List<Class<T>> list = new ArrayList<>();

    ClassLoader loader = ClassLoader.getSystemClassLoader();
    for (String binaryName : binaryNames) {
        if (binaryName.contains("$") && !includeInnerClasses) {
            log.debug("Skipped inner class: " + binaryName);
            continue;
        }//from  ww  w  .ja  v a 2s. c  om

        try {
            Class<?> clazz = loader.loadClass(binaryName);
            int modifiers = clazz.getModifiers();
            if ((modifiers & Modifier.INTERFACE) != 0 && !includeInterfaces) {
                log.debug("Skipped interface: " + binaryName);
                continue;
            }
            if ((modifiers & Modifier.ABSTRACT) != 0 && !includeAbstractClasses) {
                log.debug("Skipped abstract class: " + binaryName);
                continue;
            }
            if (needle.isAssignableFrom(clazz)) {
                log.debug("added class/interface/..: " + binaryName);
                list.add((Class<T>) clazz);
            }
        } catch (ClassNotFoundException e) {
            // This should never happen
            log.warn("couldn't find class (?!): " + binaryName, e);
        }
    }
    return list;
}