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.jsonschema2pojo.integration.json.JsonTypesIT.java

@Test
public void numberIsMappedToBigDecimal() throws Exception {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/simpleTypes.json", "com.example",
            config("sourceType", "json", "useBigDecimals", true));

    Class<?> generatedType = resultsClassLoader.loadClass("com.example.SimpleTypes");

    Object deserialisedValue = OBJECT_MAPPER
            .readValue(this.getClass().getResourceAsStream("/json/simpleTypes.json"), generatedType);

    assertThat((BigDecimal) generatedType.getMethod("getC").invoke(deserialisedValue),
            is(new BigDecimal("12999999999999999999999.99")));
}

From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java

private static synchronized void initSessionFactory(String hibfile, String mapdir, String jndiName)
        throws HibernateException {
    //ClassLoader cl1;

    if (sessionFactory == null) {

        if (jndiName == null || jndiName.trim().length() == 0)
            jndiName = CommonConstant.DEFAULT_JNDI_URL;
        Context initCtx = null;/* ww  w.  j a v  a  2 s. c  o  m*/
        try {
            initCtx = new InitialContext();
            sessionFactory = (SessionFactory) initCtx.lookup(jndiName);
            return;
        } catch (Exception e) {
            logger.log(Level.INFO, "Unable to get JNDI data source connection", e);
        } finally {
            if (initCtx != null)
                try {
                    initCtx.close();
                } catch (NamingException e) {
                    //ignore
                }
        }

        Thread thread = Thread.currentThread();
        try {
            //Class.forName("org.hibernate.Configuration");
            //Configuration ffff = new Configuration();
            //Class.forName("org.apache.commons.logging.LogFactory");

            oldloader = thread.getContextClassLoader();
            //Class thwy = oldloader.loadClass("org.hibernate.cfg.Configuration");
            //Class thwy2 = oldloader.loadClass("org.apache.commons.logging.LogFactory");
            //refreshURLs();
            //ClassLoader changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]),HibernateUtil.class.getClassLoader());
            ClassLoader testLoader = new URLClassLoader((URL[]) URLList.toArray(new URL[0]), pluginLoader);
            //changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]));

            thread.setContextClassLoader(testLoader);
            //Class thwy2 = changeLoader.loadClass("org.hibernate.cfg.Configuration");
            //Class.forName("org.apache.commons.logging.LogFactory", true, changeLoader);
            //Class cls = Class.forName("org.hibernate.cfg.Configuration", true, changeLoader);
            //Configuration cfg=null;
            //cfg = new Configuration();
            //Object oo = cls.newInstance();
            //Configuration cfg = (Configuration)oo;
            Configuration cfg = new Configuration();
            buildConfig(hibfile, mapdir, cfg);

            Class<? extends Driver> driverClass = testLoader
                    .loadClass(cfg.getProperty("connection.driver_class")).asSubclass(Driver.class);
            Driver driver = driverClass.newInstance();
            WrappedDriver wd = new WrappedDriver(driver, cfg.getProperty("connection.driver_class"));

            boolean foundDriver = false;
            Enumeration<Driver> drivers = DriverManager.getDrivers();
            while (drivers.hasMoreElements()) {
                Driver nextDriver = (Driver) drivers.nextElement();
                if (nextDriver.getClass() == wd.getClass()) {
                    if (nextDriver.toString().equals(wd.toString())) {
                        foundDriver = true;
                        break;
                    }
                }
            }
            if (!foundDriver) {

                DriverManager.registerDriver(wd);
            }

            sessionFactory = cfg.buildSessionFactory();
            //configuration = cfg;
            HibernateMapDirectory = mapdir;
            HibernateConfigFile = hibfile;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new HibernateException("No Session Factory Created " + e.getLocalizedMessage(), e);
        } finally {
            thread.setContextClassLoader(oldloader);
        }
    }
}

From source file:org.jboss.snowdrop.context.support.JBossActivationSpecBeanDefinitionParser.java

private String detectJBossActivationSpecClass(ParserContext parserContext) {
    ClassLoader classLoader = parserContext.getReaderContext().getBeanClassLoader();
    if (classLoader == null) {
        classLoader = ClassUtils.getDefaultClassLoader();
    }//from  w  w  w . ja va 2s.c  o  m
    for (String activationSpecClassNameCandidate : ACTIVATION_SPEC_CLASSNAME_CANDIDATES) {
        try {
            classLoader.loadClass(activationSpecClassNameCandidate);
            return activationSpecClassNameCandidate;
        } catch (ClassNotFoundException e) {
            // ignore
        }
    }

    throw new BeanCreationException("Cannot find a suitable ActivationSpec class on the classpath");
}

From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java

@Test
public void arrayItemsAreRecursivelyMerged() throws Exception {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/complexPropertiesInArrayItem.json",
            "com.example", config("sourceType", "json"));
    Class<?> genType = resultsClassLoader.loadClass("com.example.ComplexPropertiesInArrayItem");
    Class<?> listItemType = resultsClassLoader.loadClass("com.example.List");
    Class<?> objItemType = resultsClassLoader.loadClass("com.example.Obj");

    Object[] items = (Object[]) OBJECT_MAPPER.readValue(
            this.getClass().getResourceAsStream("/json/complexPropertiesInArrayItem.json"),
            Array.newInstance(genType, 0).getClass());
    {/*  w ww  . j ava  2s  . com*/
        Object item = items[0];

        List<?> itemList = (List<?>) genType.getMethod("getList").invoke(item);
        assertThat((Integer) listItemType.getMethod("getA").invoke(itemList.get(0)), is(1));
        assertThat((String) listItemType.getMethod("getC").invoke(itemList.get(0)), is("hey"));
        assertNull(listItemType.getMethod("getB").invoke(itemList.get(0)));

        Object itemObj = genType.getMethod("getObj").invoke(item);
        assertThat((String) objItemType.getMethod("getName").invoke(itemObj), is("k"));
        assertNull(objItemType.getMethod("getIndex").invoke(itemObj));
    }
    {
        Object item = items[1];

        List<?> itemList = (List<?>) genType.getMethod("getList").invoke(item);
        assertThat((Integer) listItemType.getMethod("getB").invoke(itemList.get(0)), is(177));
        assertThat((String) listItemType.getMethod("getC").invoke(itemList.get(0)), is("hey again"));
        assertNull(listItemType.getMethod("getA").invoke(itemList.get(0)));

        Object itemObj = genType.getMethod("getObj").invoke(item);
        assertThat((Integer) objItemType.getMethod("getIndex").invoke(itemObj), is(8));
        assertNull(objItemType.getMethod("getName").invoke(itemObj));
    }
}

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

@Test
public void additionalPropertiesOfBooleanTypeOnly()
        throws SecurityException, NoSuchMethodException, ClassNotFoundException {

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

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesPrimitiveBoolean");
    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

    assertThat(((ParameterizedType) getter.getGenericReturnType()).getActualTypeArguments()[1],
            is(equalTo((Type) Boolean.class)));

    // setter with these types should exist:
    classWithNoAdditionalProperties.getMethod("setAdditionalProperties", String.class, boolean.class);

}

From source file:net.mlw.vlh.adapter.jdbc.dynabean.fix.JDBCDynaClass.java

/**
 * <p>Loads and returns the <code>Class</code> of the given name.
 * By default, a load from the thread context class loader is attempted.
 * If there is no such class loader, the class loader used to load this
 * class will be utilized.</p>//  www . j av a2 s. c om
 *
 * @exception SQLException if an exception was thrown trying to load
 *  the specified class
 */
protected Class loadClass(String className) throws SQLException {

    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null) {
            cl = this.getClass().getClassLoader();
        }
        return (cl.loadClass(className));
    } catch (Exception e) {
        throw new SQLException("Cannot load column class '" + className + "': " + e);
    }

}

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

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

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example",
            config("customAnnotator", DeprecatingAnnotator.class.getName()));

    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()));

    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.google.gdt.eclipse.designer.gxt.databinding.model.beans.BeanSupport.java

public BeanSupport(ClassLoader classLoader, AstEditor editor, IJavaProject javaProject) throws Exception {
    m_classLoader = classLoader;//from  ww w  . ja v  a 2s  . c om
    m_editor = editor;
    m_javaProject = javaProject == null ? editor.getJavaProject() : javaProject;
    m_ModelDataClass = classLoader.loadClass("com.extjs.gxt.ui.client.data.ModelData");
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Scan a package for class files and add their metadata to a taglib model
 * @param pkg the package to scan//  w ww  . ja  va  2s . co m
 * @param taglib the taglib model
 * @param loader the class loader to use
 * @param lookInsideJars whether to look inside jars
 */
public void addLocalMetadata(String pkg, JspTaglibModel taglib, ClassLoader loader, boolean lookInsideJars) {
    Collection<String> classes = scanClasspath(pkg, loader, lookInsideJars);
    for (String className : classes) {
        try {
            Class<?> cls = loader.loadClass(className);
            addMetadata(cls, taglib);
        } catch (ClassNotFoundException e) {
            s_log.warn("couldn't load class", e);
        }
    }
}