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:com.googlecode.jsonschema2pojo.integration.PropertiesIT.java

@Test
@SuppressWarnings("rawtypes")
public void usePrimitivesArgumentCausesPrimitiveTypes() throws ClassNotFoundException, IntrospectionException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

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

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

    assertThat(new PropertyDescriptor("a", generatedType).getReadMethod().getReturnType().getName(), is("int"));
    assertThat(new PropertyDescriptor("b", generatedType).getReadMethod().getReturnType().getName(),
            is("double"));
    assertThat(new PropertyDescriptor("c", generatedType).getReadMethod().getReturnType().getName(),
            is("boolean"));

}

From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderRenderer.java

private void setObjects(Object binder) throws Exception {
    ClassLoader classLoader = binder.getClass().getClassLoader();
    String handlerClassName = binder.getClass().getName() + "$DTObjectHandler";
    Class<?> handlerClass = classLoader.loadClass(handlerClassName);
    Object handler = Proxy.newProxyInstance(classLoader, new Class[] { handlerClass }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("handle")) {
                String path = (String) args[0];
                Object object = args[1];
                XmlObjectInfo objectInfo = m_pathToModelMap.get(path);
                objectInfo.setObject(object);
            }//  ww w.  j a  v  a2  s .com
            if (method.getName().equals("provideFactory")) {
                Class<?> factoryType = (Class<?>) args[0];
                String methodName = (String) args[1];
                Object[] factoryArgs = (Object[]) args[2];
                return UiBinderParser.createProvidedFactory(m_context, factoryType, methodName, factoryArgs);
            }
            if (method.getName().equals("provideField")) {
                Class<?> fieldType = (Class<?>) args[0];
                String fieldName = (String) args[1];
                return UiBinderParser.createProvidedField(m_context, fieldType, fieldName);
            }
            return null;
        }
    });
    ReflectionUtils.setField(binder, "dtObjectHandler", handler);
}

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

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

    ClassLoader resultsClassLoader = schemaRule.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:org.jsonschema2pojo.integration.config.Moshi1IT.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test//w  w  w  .  ja v a2 s .com
public void enumValuesAreSerializedCorrectly()
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/typeWithEnumProperty.json",
            "com.example", config("annotationStyle", "moshi1", "propertyWordDelimiters", "_"));

    Class generatedType = resultsClassLoader.loadClass("com.example.TypeWithEnumProperty");
    Class enumType = resultsClassLoader.loadClass("com.example.TypeWithEnumProperty$EnumProperty");
    Object instance = generatedType.newInstance();

    Method setter = generatedType.getMethod("setEnumProperty", enumType);
    setter.invoke(instance, enumType.getEnumConstants()[3]);

    JsonAdapter jsonAdapter = moshi.adapter(generatedType);
    String json = jsonAdapter.toJson(instance);

    Map<String, String> jsonAsMap = new Gson().fromJson(json, Map.class);
    assertThat(jsonAsMap.get("enum_Property"), is("4 ! 1"));
}

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

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

    ClassLoader resultsClassLoader = schemaRule.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:com.bfd.harpc.config.spring.ClientBean.java

@Override
@JSONField(serialize = false)/*from   ww w.ja  v  a 2s. c  o m*/
public Class getObjectType() {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    // Iface?
    Class<?> objectClass = null;
    try {
        objectClass = classLoader.loadClass(getIface());
    } catch (ClassNotFoundException e) {
    }
    return objectClass;
}

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

@Override
public void actionPerformed(final ActionEvent e) {
    try {/*from w  ww . j a v a 2 s .  co m*/
        GnucashWritableFile wModel = myJGnucashEditor.getWritableModel();
        if (wModel == null) {
            JOptionPane.showMessageDialog(myJGnucashEditor, "No open file.",
                    "Please open a gnucash-file first!", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 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 ImporterPlugin)) {
            LOGGER.error("Plugin '" + pluginName + "' does not implement ImporterPlugin-interface.");
            JOptionPane.showMessageDialog(myJGnucashEditor, "Error",
                    "Plugin '" + pluginName + "' does not implement ImporterPlugin-interface.",
                    JOptionPane.ERROR_MESSAGE);
            return;

        }
        ImporterPlugin importer = (ImporterPlugin) o;
        try {
            myJGnucashEditor.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            GnucashWritableAccount selectedAccount = (GnucashWritableAccount) myJGnucashEditor
                    .getSelectedAccount();
            String message = importer.runImport(wModel, selectedAccount);
            if (message != null && message.length() > 0) {
                JOptionPane.showMessageDialog(myJGnucashEditor, "Import OK",
                        "The import was a success:\n" + message, JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception e1) {
            LOGGER.error("Import via Plugin '" + pluginName + "' failed.", e1);
            JOptionPane
                    .showMessageDialog(
                            myJGnucashEditor, "Error", "Import 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 import-plugin '" + pluginName + "'.", e1);
        JOptionPane
                .showMessageDialog(
                        myJGnucashEditor, "Error", "Could not activate requested import-plugin '" + pluginName
                                + "'.\n" + "[" + e1.getClass().getName() + "]: " + e1.getMessage(),
                        JOptionPane.ERROR_MESSAGE);
    }
}

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

@Override
public void actionPerformed(final ActionEvent e) {
    try {/*from   w w w.java 2s  .com*/
        GnucashWritableFile wModel = myJGnucashEditor.getWritableModel();
        if (wModel == null) {
            JOptionPane.showMessageDialog(myJGnucashEditor, "No open file.",
                    "Please open a gnucash-file first!", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 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 ToolPlugin)) {
            LOGGER.error("Plugin '" + pluginName + "' does not implement ToolPlugin-interface.");
            JOptionPane.showMessageDialog(myJGnucashEditor, "Error",
                    "Plugin '" + pluginName + "' does not implement ToolPlugin-interface.",
                    JOptionPane.ERROR_MESSAGE);
            return;

        }
        ToolPlugin importer = (ToolPlugin) o;
        try {
            myJGnucashEditor.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            GnucashWritableAccount selectedAccount = (GnucashWritableAccount) myJGnucashEditor
                    .getSelectedAccount();
            String message = importer.runTool(wModel, selectedAccount);
            if (message != null && message.length() > 0) {
                JOptionPane.showMessageDialog(myJGnucashEditor, "Tool OK",
                        "The tool-use was a success:\n" + message, JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception e1) {
            LOGGER.error("Tool-use via Plugin '" + pluginName + "' failed.", e1);
            JOptionPane
                    .showMessageDialog(
                            myJGnucashEditor, "Error", "Tool-use 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 Tool-plugin '" + pluginName + "'.", e1);
        JOptionPane
                .showMessageDialog(
                        myJGnucashEditor, "Error", "Could not activate requested Tool-plugin '" + pluginName
                                + "'.\n" + "[" + e1.getClass().getName() + "]: " + e1.getMessage(),
                        JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.jsonschema2pojo.integration.PropertiesIT.java

@Test
@SuppressWarnings("rawtypes")
public void propertiesWithNullValuesAreOmittedWhenSerialized() throws ClassNotFoundException,
        IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/nullProperties.json",
            "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.NullProperties");
    Object instance = generatedType.newInstance();

    Method setter = new PropertyDescriptor("property", generatedType).getWriteMethod();
    setter.invoke(instance, "value");

    assertThat(mapper.valueToTree(instance).toString(), containsString("property"));

    setter.invoke(instance, (Object) null);

    assertThat(mapper.valueToTree(instance).toString(), not(containsString("property")));

}

From source file:com.redhat.rhn.frontend.taglibs.list.RowRendererTag.java

/**
 * {@inheritDoc}/*from  w w  w  .ja va2  s  .c  om*/
 */
public int doEndTag() throws JspException {
    ListCommand command = ListTagUtil.getCurrentCommand(this, pageContext);
    if (command.equals(ListCommand.ENUMERATE)) {
        if (!StringUtils.isBlank(name)) {
            ListTag parent = (ListTag) BodyTagSupport.findAncestorWithClass(this, ListTag.class);

            try {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();

                if (name.indexOf('.') == -1) {
                    name = "com.redhat.rhn.frontend.taglibs.list.row." + name;
                }
                RowRenderer row = (RowRenderer) cl.loadClass(name).newInstance();
                if (!StringUtils.isEmpty(classes)) {
                    row.setRowClasses(classes);
                }
                parent.setRowRenderer(row);

            } catch (Exception e) {
                String msg = "Exception while adding Decorator [" + name + "]";
                throw new JspException(msg, e);
            }
        }
    }
    return super.doEndTag();
}