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.EnumIT.java

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

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

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

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

}

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

/**
 * Handle object before setting attributes, so get default property values.
 *//*from w w  w .  ja v a2s .c o  m*/
private void createModels(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];
                createModel(path, object);
            }
            if (method.getName().equals("provideFactory")) {
                Class<?> factoryType = (Class<?>) args[0];
                String methodName = (String) args[1];
                Object[] factoryArgs = (Object[]) args[2];
                return createProvidedFactory(m_context, factoryType, methodName, factoryArgs);
            }
            if (method.getName().equals("provideField")) {
                Class<?> fieldType = (Class<?>) args[0];
                String fieldName = (String) args[1];
                return createProvidedField(m_context, fieldType, fieldName);
            }
            return null;
        }
    });
    ReflectionUtils.setField(binder, "dtObjectHandler", handler);
}

From source file:org.codehaus.grepo.core.config.GenericRepositoryScanBeanDefinitionParser.java

/**
 * @param element The element.//from w  ww  .jav a2 s .  c o  m
 * @param classLoader The class loader.
 * @return Returns the type filter.
 */
@SuppressWarnings("unchecked")
protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) {
    String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
    String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
    try {
        if ("annotation".equals(filterType)) {
            return new AnnotationTypeFilter((Class<Annotation>) classLoader.loadClass(expression));
        } else if ("assignable".equals(filterType)) {
            return new AssignableTypeFilter(classLoader.loadClass(expression));
        } else if ("aspectj".equals(filterType)) {
            return new AspectJTypeFilter(expression, classLoader);
        } else if ("regex".equals(filterType)) {
            return new RegexPatternTypeFilter(Pattern.compile(expression));
        } else if ("custom".equals(filterType)) {
            Class filterClass = classLoader.loadClass(expression);
            if (!TypeFilter.class.isAssignableFrom(filterClass)) {
                throw new IllegalArgumentException(
                        "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
            }
            return (TypeFilter) BeanUtils.instantiateClass(filterClass);
        } else {
            throw new IllegalArgumentException("Unsupported filter type: " + filterType);
        }
    } catch (ClassNotFoundException ex) {
        throw new FatalBeanException("Type filter class not found: " + expression, ex);
    }
}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.RDBMSDataConnectorBeanDefinitionParser.java

/**
 * Builds a JDBC {@link javax.sql.DataSource} from an ApplicationManagedConnection configuration element.
 * //www  .j ava  2s .  co  m
 * @param pluginId ID of this data connector
 * @param amc the application managed configuration element
 * 
 * @return the built data source
 */
protected DataSource buildApplicationManagedConnection(String pluginId, Element amc) {
    ComboPooledDataSource datasource = new ComboPooledDataSource();

    String driverClass = DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcDriver"));
    ClassLoader classLoader = this.getClass().getClassLoader();
    try {
        classLoader.loadClass(driverClass);
    } catch (ClassNotFoundException e) {
        log.error(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
        throw new BeanCreationException(
                "Unable to create relational database connector, JDBC driver can not be found on the classpath");
    }

    try {
        datasource.setDriverClass(driverClass);
        datasource.setJdbcUrl(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcURL")));
        datasource.setUser(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcUserName")));
        datasource.setPassword(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "jdbcPassword")));

        if (amc.hasAttributeNS(null, "poolAcquireIncrement")) {
            datasource.setAcquireIncrement(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireIncrement"))));
        } else {
            datasource.setAcquireIncrement(3);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryAttempts")) {
            datasource.setAcquireRetryAttempts(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryAttempts"))));
        } else {
            datasource.setAcquireRetryAttempts(36);
        }

        if (amc.hasAttributeNS(null, "poolAcquireRetryDelay")) {
            datasource.setAcquireRetryDelay(Integer
                    .parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolAcquireRetryDelay"))));
        } else {
            datasource.setAcquireRetryDelay(5000);
        }

        if (amc.hasAttributeNS(null, "poolBreakAfterAcquireFailure")) {
            datasource.setBreakAfterAcquireFailure(XMLHelper
                    .getAttributeValueAsBoolean(amc.getAttributeNodeNS(null, "poolBreakAfterAcquireFailure")));
        } else {
            datasource.setBreakAfterAcquireFailure(true);
        }

        if (amc.hasAttributeNS(null, "poolMinSize")) {
            datasource.setMinPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMinSize"))));
        } else {
            datasource.setMinPoolSize(2);
        }

        if (amc.hasAttributeNS(null, "poolMaxSize")) {
            datasource.setMaxPoolSize(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxSize"))));
        } else {
            datasource.setMaxPoolSize(50);
        }

        if (amc.hasAttributeNS(null, "poolMaxIdleTime")) {
            datasource.setMaxIdleTime(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolMaxIdleTime"))));
        } else {
            datasource.setMaxIdleTime(600);
        }

        if (amc.hasAttributeNS(null, "poolIdleTestPeriod")) {
            datasource.setIdleConnectionTestPeriod(
                    Integer.parseInt(DatatypeHelper.safeTrim(amc.getAttributeNS(null, "poolIdleTestPeriod"))));
        } else {
            datasource.setIdleConnectionTestPeriod(180);
        }

        log.debug("Created application managed data source for data connector {}", pluginId);
        return datasource;
    } catch (PropertyVetoException e) {
        log.error("Unable to create data source for data connector {} with JDBC driver class {}", pluginId,
                driverClass);
        return null;
    }
}

From source file:com.consol.citrus.admin.service.TestCaseService.java

/**
 * Get test case model from Java source code.
 * @param project//from  www.ja  v a  2 s  .  c om
 * @param detail
 * @return
 */
private TestcaseModel getJavaTestModel(Project project, TestDetail detail) {
    if (project.isMavenProject()) {
        try {
            FileUtils.setSimulationMode(true);
            ClassLoader classLoader = getTestClassLoader(project);
            Class testClass = classLoader.loadClass(detail.getPackageName() + "." + detail.getClassName());

            if (TestSimulator.class.isAssignableFrom(testClass)) {
                TestSimulator testInstance = (TestSimulator) testClass.newInstance();
                Method testMethod = ReflectionUtils.findMethod(testClass, detail.getMethodName());

                Mocks.injectMocks(testInstance);

                testInstance.simulate(testMethod, Mocks.getTestContextMock(),
                        Mocks.getApplicationContextMock());
                testMethod.invoke(testInstance);

                return getTestcaseModel(testInstance.getTestCase());
            } else {
                throw new ApplicationRuntimeException("Unsupported test case type: " + testClass);
            }
        } catch (MalformedURLException e) {
            throw new ApplicationRuntimeException("Failed to access Java classes output folder", e);
        } catch (ClassNotFoundException | NoClassDefFoundError e) {
            log.error("Failed to load Java test class", e);
        } catch (IOException e) {
            throw new ApplicationRuntimeException("Failed to access project output folder", e);
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("Failed to create test class instance", e);
        } catch (InvocationTargetException e) {
            log.error("Failed to invoke test method", e);
        } finally {
            FileUtils.setSimulationMode(false);
        }
    }

    TestcaseModel testModel = new TestcaseModel();
    testModel.setName(detail.getClassName() + "." + detail.getMethodName());
    return testModel;
}

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

@Test
@SuppressWarnings({ "unchecked" })
public void enumWithCustomJavaNames() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException, IOException {

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

    Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.EnumWithCustomJavaNames");
    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.EnumWithCustomJavaNames$EnumProperty");

    Object valueWithEnumProperty = typeWithEnumProperty.newInstance();
    Method enumSetter = typeWithEnumProperty.getMethod("setEnumProperty", enumClass);
    enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[2]);
    assertThat(enumClass.getEnumConstants()[0].name(), is("ONE"));
    assertThat(enumClass.getEnumConstants()[1].name(), is("TWO"));
    assertThat(enumClass.getEnumConstants()[2].name(), is("THREE"));
    assertThat(enumClass.getEnumConstants()[3].name(), is("FOUR"));

    ObjectMapper objectMapper = new ObjectMapper();

    String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
    JsonNode jsonTree = objectMapper.readTree(jsonString);

    assertThat(jsonTree.size(), is(1));/*from w  w  w. j  a v a2s.c  om*/
    assertThat(jsonTree.has("enum_Property"), is(true));
    assertThat(jsonTree.get("enum_Property").isTextual(), is(true));
    assertThat(jsonTree.get("enum_Property").asText(), is("3"));
}

From source file:com.opengamma.maven.scripts.ScriptableScriptGeneratorMojo.java

private Template getTemplateForClass(String className, ClassLoader classLoader,
        Map<Class<?>, Template> templateMap) throws MojoExecutionException {
    if (templateMap.size() == 1 && Object.class.equals(Iterables.getOnlyElement(templateMap.keySet()))) {
        return Iterables.getOnlyElement(templateMap.values());
    }/*from  w  ww  . jav  a 2  s .c  om*/
    Class<?> clazz;
    try {
        clazz = classLoader.loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException("Unable to resolve class " + className);
    }
    for (Map.Entry<Class<?>, Template> templateMapEntry : templateMap.entrySet()) {
        if (templateMapEntry.getKey().isAssignableFrom(clazz)) {
            return templateMapEntry.getValue();
        }
    }
    return null;
}

From source file:com.alibaba.dragoon.patrol.PatrolUtils.java

public static void registerMBean(boolean useJndiDataSource, ClassLoader containerClassLoader,
        boolean springStatEnable, boolean jdbcStatEnable, boolean uriStatEnable, boolean log4jStatEnable,
        boolean napoliStatEnable, boolean napoliMQServerStatEnable) {

    JMXUtils.register(BEAN_NAME_KV_STATS, KVStatManager.getInstance());
    // JMXUtils.register(BEAN_NAME_BROWSER_STATS, BrowserStatManager.getInstance());

    if (springStatEnable) {
        JMXUtils.register(BEAN_NAME_SPRING_STAT, SpringStatManager.getInstance());
        JMXUtils.register(BEAN_NAME_SPRING_METHOD_STAT, SpringStatManager.getInstance().getMethodStat());
        JMXUtils.register(BEAN_NAME_SPRING_IBATIS_STAT, SpringStatManager.getInstance().getIbatisStat());
    }//from w w w. j av  a2  s  . c  o  m

    if (uriStatEnable) {
        JMXUtils.register(BEAN_NAME_WEB_STAT, WebStatisticManager.getInstance());
    }

    if (log4jStatEnable) {
        JMXUtils.register(BEAN_NAME_LOG_STAT, LogStatManager.getInstance());
        // TODO remove it
        JMXUtils.register(BEAN_NAME_EXCEPTION, LogStatManager.getInstance()); // 
    }

    JMXUtils.register(BEAN_NAME_TRACE, TraceManager.getInstance());

    if (jdbcStatEnable) {
        if (useJndiDataSource) {
            try {
                Class<?> clazz = null;

                try {
                    clazz = containerClassLoader.loadClass("com.alibaba.druid.stat.JdbcStatManager");
                } catch (ClassNotFoundException ex) {
                    LOG.warn(ex.getMessage(), ex);
                }

                if (clazz != null) {
                    Object inst = clazz.getMethod("getInstance").invoke(null);
                    JMXUtils.register(BEAN_NAME_JDBC_STAT, inst);

                    Object connStat = clazz.getMethod("getConnectionstat").invoke(inst);
                    JMXUtils.register(BEAN_NAME_JDBC_CONNECT_STAT, connStat);

                    Object statementStat = clazz.getMethod("getStatementStat").invoke(inst);
                    JMXUtils.register(BEAN_NAME_JDBC_STATEMENT_STAT, statementStat);

                    Object resultSetStat = clazz.getMethod("getResultSetStat").invoke(inst);
                    JMXUtils.register(BEAN_NAME_JDBC_RESULTSET_STAT, resultSetStat);

                    Class<?> traceClazz = containerClassLoader
                            .loadClass("com.alibaba.druid.stat.JdbcTraceManager");
                    Object traceInst = traceClazz.getMethod("getInstance").invoke(null);
                    JMXUtils.register(BEAN_NAME_JDBC_TRACE, traceInst);

                    Class<?> dataSourceStatManagerClazz = containerClassLoader
                            .loadClass("com.alibaba.druid.stat.DruidDataSourceStatManager");
                    Object dataSourceStatManagerInst = dataSourceStatManagerClazz.getMethod("getInstance")
                            .invoke(null);
                    JMXUtils.register(BEAN_NAME_DATASOURCE_STAT, dataSourceStatManagerInst);
                } else {
                    registerJDBCMBean();
                }
            } catch (Exception ex) {
                LOG.error("register jdbc stat error", ex);
            }
        } else {
            registerJDBCMBean();
        }
    }

    // added by chris
    if (napoliStatEnable) {
        JMXUtils.register(BEAN_NAME_NAPOLI_STAT, NapoliStatManager.getInstance());
    }
    if (napoliMQServerStatEnable) {
        JMXUtils.register(BEAN_NAME_NAPOLI_MQSERVER_STAT, NapoliMQServerStatManager.getInstance());
    }
}

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

@Test
@SuppressWarnings("unchecked")
public void enumWithNoValidCharactersForIdentifier() throws Exception {

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

    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.EnumWithNoValidCharactersForIdentifier");

    assertThat(enumClass.getEnumConstants()[0].name(), is("__EMPTY__"));
    assertThat(enumClass.getEnumConstants()[1].name(), is("__EMPTY___"));
    assertThat(enumClass.getEnumConstants()[2].name(), is("__EMPTY____"));

    assertThat(enumClass.getEnumConstants()[0].toString(), is(":"));
    assertThat(enumClass.getEnumConstants()[1].toString(), is("\u2265"));
    assertThat(enumClass.getEnumConstants()[2].toString(), is("<"));
}

From source file:com.alibaba.rocketmq.filtersrv.filter.DynaCode.java

private void loadClass(Set<String> classFullNames) throws ClassNotFoundException, MalformedURLException {
    synchronized (loadClass) {
        ClassLoader classLoader = new URLClassLoader(new URL[] { new File(outPutClassPath).toURI().toURL() },
                parentClassLoader);/*from  w ww. j av  a 2  s  .com*/
        for (String key : classFullNames) {
            Class<?> classz = classLoader.loadClass(key);
            if (null != classz) {
                loadClass.put(key, classz);
                logger.info("Dyna Load Java Class File OK:----> className: " + key);
            } else {
                logger.error("Dyna Load Java Class File Fail:----> className: " + key);
            }
        }
    }
}