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:org.codehaus.grepo.core.config.GenericRepositoryScanBeanDefinitionParser.java

/**
 * @param className The class name.//from   w w  w  . j  a v a2s  .c  o  m
 * @param strategyType The strategy type.
 * @param classLoader The class loader.
 * @return Returns the newly created instance.
 */
@SuppressWarnings("unchecked")
private Object instantiateUserDefinedStrategy(String className, Class strategyType, ClassLoader classLoader) {
    Object result = null;
    try {
        result = classLoader.loadClass(className).newInstance();
    } catch (ClassNotFoundException ex) {
        throw new IllegalArgumentException(
                "Class [" + className + "] for strategy [" + strategyType.getName() + "] not found", ex);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Unable to instantiate class [" + className + "] for strategy ["
                + strategyType.getName() + "]. A zero-argument constructor is required", ex);
    }

    if (!strategyType.isAssignableFrom(result.getClass())) {
        throw new IllegalArgumentException("Provided class name must be an implementation of " + strategyType);
    }
    return result;
}

From source file:gridool.GridServer.java

@SuppressWarnings("unchecked")
@Override//from w  ww.j ava  2 s.c o  m
public <A extends Serializable, R extends Serializable> R execute(GridJobDesc jobDesc, A arg)
        throws RemoteException {
    String jobClassName = jobDesc.getJobClass();
    String deployGroup = jobDesc.getDeploymentGroup();

    ClassLoader cl = registry.getDeploymentGroupClassLoader(deployGroup);
    final Class<? extends GridJob<A, R>> jobClass;
    try {
        jobClass = (Class<? extends GridJob<A, R>>) cl.loadClass(jobClassName);
    } catch (ClassNotFoundException e) {
        throw new RemoteException("Class not found: " + jobClassName, e);
    }
    return execute(jobClass, arg, deployGroup);
}

From source file:com.googlecode.jsonschema2pojo.integration.config.AnnotationStyleIT.java

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

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("annotationStyle", "none"));

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

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

    assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue()));
    assertThat(generatedType.getAnnotation(JsonSerialize.class), is(nullValue()));
    assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue()));

}

From source file:com.googlecode.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void enumWithEmptyStringAsValue() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/enum/enumWithEmptyString.json", "com.example");

    Class<Enum> emptyEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithEmptyString");

    assertThat(emptyEnumClass.getEnumConstants()[0].name(), is("__EMPTY__"));

}

From source file:com.freetmp.common.util.ClassUtils.java

public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
    if (classLoader == null) {
        return true;
    }//from www.  j a v  a  2s .com
    try {
        Class<?> actualClass = classLoader.loadClass(clazz.getName());
        return (clazz == actualClass);
        // Else: different interface class found...
    } catch (ClassNotFoundException ex) {
        // No interface class found...
        return false;
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.config.AnnotationStyleIT.java

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

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("annotationStyle", "jackson"));

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

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

    assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue()));
    assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue()));
}

From source file:org.apache.hadoop.gateway.dispatch.GatewayDispatchFilter.java

private <T> Class<T> loadClass(String className) throws ClassNotFoundException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader == null) {
        loader = this.getClass().getClassLoader();
    }/*from w w  w  . ja  v  a 2 s  . com*/
    return (Class<T>) loader.loadClass(className);
}

From source file:biz.wolschon.finance.jgnucash.actions.SaveAsFilePluginMenuAction.java

@Override
public void actionPerformed(final ActionEvent e) {
    try {//from ww  w .ja va  2  s  . c om

        // Activate plug-in that declares extension.
        myJGnucashEditor.getPluginManager().activatePlugin(ext.getDeclaringPluginDescriptor().getId());
        // Get plug-in class loader.
        ClassLoader classLoader = myJGnucashEditor.getPluginManager()
                .getPluginClassLoader(ext.getDeclaringPluginDescriptor());
        // Load Tool class.
        Class toolCls = classLoader.loadClass(ext.getParameter("class").valueAsString());
        // Create Tool instance.
        Object o = toolCls.newInstance();
        if (!(o instanceof DataSourcePlugin)) {
            LOGGER.error("Plugin '" + pluginName + "' does not implement DataSourcePlugin-interface.");
            JOptionPane.showMessageDialog(myJGnucashEditor, "Error",
                    "Plugin '" + pluginName + "' does not implement DataSourcePlugin-interface.",
                    JOptionPane.ERROR_MESSAGE);
            return;

        }
        DataSourcePlugin importer = (DataSourcePlugin) o;
        try {
            myJGnucashEditor.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //workaround because of a deadlock in log4j-consoleAppender in the JPf-classloader
            Logger.getLogger("org.java.plugin.standard.StandardPluginClassLoader").removeAllAppenders();
            Logger.getLogger("org.java.plugin.standard.StandardPluginClassLoader").setLevel(Level.FATAL);
            importer.writeTo(myJGnucashEditor.getWritableModel());
        } catch (Exception e1) {
            LOGGER.error("Write via Plugin '" + pluginName + "' failed.", e1);
            JOptionPane
                    .showMessageDialog(
                            myJGnucashEditor, "Error", "Write via Plugin '" + pluginName + "' failed.\n" + "["
                                    + e1.getClass().getName() + "]: " + e1.getMessage(),
                            JOptionPane.ERROR_MESSAGE);
        } finally {
            myJGnucashEditor.setCursor(Cursor.getDefaultCursor());
        }
    } catch (Exception e1) {
        LOGGER.error("Could not activate requested Writer-plugin '" + pluginName + "'.", e1);
        JOptionPane
                .showMessageDialog(
                        myJGnucashEditor, "Error", "Could not activate requested Writer-plugin '" + pluginName
                                + "'.\n" + "[" + e1.getClass().getName() + "]: " + e1.getMessage(),
                        JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java

/**
 * Constructs a list of widget configurations based on the information
 * provided by classes annotated as Widgets.
 * //from   w  w w  .ja  v a  2s .c o  m
 * @param classPool
 * @param classLoader
 * @param reflections
 * @return The constructed widget configurations
 * @throws ClassNotFoundException
 * @throws NotFoundException
 * @throws MalformedURLException
 */
public static List<WidgetConfigHolder> getAllWidgetAnnotations(ClassPool classPool, ClassLoader classLoader,
        Reflections reflections) throws ClassNotFoundException, NotFoundException, MalformedURLException {
    List<WidgetConfigHolder> builtInWidgets = new ArrayList<WidgetConfigHolder>();

    for (Class<?> c : reflections.getTypesAnnotatedWith(Widget.class)) {
        CtClass clazz = classPool.getCtClass(c.getName());
        Widget widgetAnnotation = (Widget) clazz.getAnnotation(Widget.class);

        Class<? extends Annotation> annotationClass = widgetAnnotation.annotationClass();

        Class<? extends WidgetMaker> makerClass = widgetAnnotation.makerClass();
        Class<? extends AbstractWidget> widgetClass = classLoader.loadClass(clazz.getName())
                .asSubclass(AbstractWidget.class);
        WidgetConfigHolder widgetConfig = new WidgetConfigHolder(annotationClass, widgetClass, makerClass,
                widgetAnnotation.xtype(), widgetAnnotation.ranking());

        builtInWidgets.add(widgetConfig);

    }
    return builtInWidgets;
}

From source file:biz.wolschon.finance.jgnucash.actions.OpenFilePluginMenuAction.java

@Override
public void actionPerformed(final ActionEvent e) {
    try {//ww  w  .ja va 2 s  .co m

        // Activate plug-in that declares extension.
        myJGnucashEditor.getPluginManager().activatePlugin(ext.getDeclaringPluginDescriptor().getId());
        // Get plug-in class loader.
        ClassLoader classLoader = myJGnucashEditor.getPluginManager()
                .getPluginClassLoader(ext.getDeclaringPluginDescriptor());
        // Load Tool class.
        Class toolCls = classLoader.loadClass(ext.getParameter("class").valueAsString());
        // Create Tool instance.
        Object o = toolCls.newInstance();
        if (!(o instanceof DataSourcePlugin)) {
            LOGGER.error("Plugin '" + pluginName + "' does not implement DataSourcePlugin-interface.");
            JOptionPane.showMessageDialog(myJGnucashEditor, "Error",
                    "Plugin '" + pluginName + "' does not implement DataSourcePlugin-interface.",
                    JOptionPane.ERROR_MESSAGE);
            return;

        }
        DataSourcePlugin importer = (DataSourcePlugin) o;
        try {
            myJGnucashEditor.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //workaround because of a deadlock in log4j-consoleAppender in the JPf-classloader
            Logger.getLogger("org.java.plugin.standard.StandardPluginClassLoader").removeAllAppenders();
            Logger.getLogger("org.java.plugin.standard.StandardPluginClassLoader").setLevel(Level.FATAL);
            GnucashWritableFile loadedFile = importer.loadFile();
            if (loadedFile != null) {
                myJGnucashEditor.setWritableModel(loadedFile);
            }
        } catch (Exception e1) {
            LOGGER.error("Load via Plugin '" + pluginName + "' failed.", e1);
            JOptionPane
                    .showMessageDialog(
                            myJGnucashEditor, "Error", "Load via Plugin '" + pluginName + "' failed.\n" + "["
                                    + e1.getClass().getName() + "]: " + e1.getMessage(),
                            JOptionPane.ERROR_MESSAGE);
        } finally {
            myJGnucashEditor.setCursor(Cursor.getDefaultCursor());
        }
    } catch (Exception e1) {
        LOGGER.error("Could not activate requested Loader-plugin '" + pluginName + "'.", e1);
        JOptionPane
                .showMessageDialog(
                        myJGnucashEditor, "Error", "Could not activate requested Loader-plugin '" + pluginName
                                + "'.\n" + "[" + e1.getClass().getName() + "]: " + e1.getMessage(),
                        JOptionPane.ERROR_MESSAGE);
    }
}