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

private void finishBinding(Expression grid, Expression bindingElement, IDatabindingsProvider iprovider)
        throws Exception {
    DatabindingsProvider provider = DatabindingsProvider.cast(iprovider);
    BeansObserveTypeContainer beansContainer = provider.getBeansContainer();
    WidgetsObserveTypeContainer widgetsContainer = provider.getWidgetsContainer();
    ////from  ww  w.  j  a  va2s  .c  o  m
    WidgetObserveInfo gridWidget = widgetsContainer.getBindableWidget(grid);
    m_model = gridWidget;
    m_modelProperty = gridWidget.getSelfProperty();
    //
    ClassLoader classLoader = CoreUtils.classLoader(provider.getJavaInfoRoot());
    String bindingElementClassName = AstNodeUtils.getFullyQualifiedName(bindingElement, true);
    Class<?> bindingElementClass = classLoader.loadClass(bindingElementClassName);
    //
    m_gridSelectionModel = new BeanObserveInfo(beansContainer.getBeanSupport(), m_modelProperty,
            bindingElementClass);
    gridWidget.getSelfProperty()
            .setProperties(m_gridSelectionModel.getChildren(ChildrenContext.ChildrenForPropertiesTable));
    //
    for (FieldBindingInfo binding : m_fieldBindings) {
        binding.setModel(m_model,
                m_gridSelectionModel.resolvePropertyReference(binding.getParsedProperty(), null));
        binding.setGridSelectionModel(m_gridSelectionModel);
    }
    //
    int index = provider.getBindings().indexOf(this);
    provider.getBindings().addAll(index + 1, m_fieldBindings);
    //
    if (m_autobind) {
        createAutobindings(m_fieldBindings, true);
    }
}

From source file:com.baomidou.hibernateplus.HibernateSpringSessionFactoryBuilder.java

/**
 * Perform Spring-based scanning for entity classes, registering them
 * as annotated classes with this {@code Configuration}.
 *
 * @param packagesToScan one or more Java package names
 * @throws HibernateException if scanning fails for any reason
 *///from ww  w .j a v  a2  s.  co m
@SuppressWarnings("unchecked")
public HibernateSpringSessionFactoryBuilder scanPackages(String... packagesToScan) throws HibernateException {
    Set<String> entityClassNames = new TreeSet<String>();
    Set<String> converterClassNames = new TreeSet<String>();
    Set<String> packageNames = new TreeSet<String>();
    try {
        for (String pkg : packagesToScan) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                    + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = this.resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(
                    this.resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        entityClassNames.add(className);
                    } else if (CONVERTER_TYPE_FILTER.match(reader, readerFactory)) {
                        converterClassNames.add(className);
                    } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                        packageNames
                                .add(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                    }
                }
            }
        }
    } catch (IOException ex) {
        throw new MappingException("Failed to scan classpath for unlisted classes", ex);
    }
    try {
        ClassLoader cl = this.resourcePatternResolver.getClassLoader();
        for (String className : entityClassNames) {
            Class<?> cls = cl.loadClass(className);
            // TODO Caratacus ? EntityInfo 
            EntityInfoUtils.initEntityInfo(cls);
            addAnnotatedClass(cls);
        }
        for (String className : converterClassNames) {
            addAttributeConverter((Class<? extends AttributeConverter<?, ?>>) cl.loadClass(className));
        }
        for (String packageName : packageNames) {
            addPackage(packageName);
        }
    } catch (ClassNotFoundException ex) {
        throw new MappingException("Failed to load annotated classes from classpath", ex);
    }
    return this;
}

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

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

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/additionalPropertiesArraysOfStrings.json", "com.example",
            config("generateBuilders", true));

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

    ParameterizedType listType = (ParameterizedType) ((ParameterizedType) getter.getGenericReturnType())
            .getActualTypeArguments()[1];
    assertThat(listType.getActualTypeArguments()[0], is(equalTo((Type) String.class)));

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

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            List.class);
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}

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

@Test
@SuppressWarnings("unchecked")
public void intEnumIsDeserializedCorrectly()
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
        JsonParseException, JsonMappingException, IOException {

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

    // the schema for a valid instance
    Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize");
    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.enums.IntegerEnumToSerialize$TestEnum");

    // read the instance into the type
    ObjectMapper objectMapper = new ObjectMapper();
    Object valueWithEnumProperty = objectMapper.readValue("{\"testEnum\" : 2}", typeWithEnumProperty);

    Method getEnumMethod = typeWithEnumProperty.getDeclaredMethod("getTestEnum");
    Method getValueMethod = enumClass.getDeclaredMethod("value");

    // call getTestEnum on the value
    assertThat(getEnumMethod, is(notNullValue()));
    Object enumObject = getEnumMethod.invoke(valueWithEnumProperty);

    // assert that the object returned is a) a TestEnum, and b) calling .value() on it returns 2
    // as per the json snippet above
    assertThat(enumObject, IsInstanceOf.instanceOf(enumClass));
    assertThat(getValueMethod, is(notNullValue()));
    assertThat((Integer) getValueMethod.invoke(enumObject), is(2));
}

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

@Test
@SuppressWarnings("unchecked")
public void intEnumIsSerializedCorrectly()
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
        JsonParseException, JsonMappingException, IOException, InstantiationException {

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

    // the schema for a valid instance
    Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize");
    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.enums.IntegerEnumToSerialize$TestEnum");

    // create an instance
    Object valueWithEnumProperty = typeWithEnumProperty.newInstance();
    Method enumSetter = typeWithEnumProperty.getMethod("setTestEnum", enumClass);

    // call setTestEnum(TestEnum.ONE)
    enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[0]);

    ObjectMapper objectMapper = new ObjectMapper();

    // write our instance out to json
    String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
    JsonNode jsonTree = objectMapper.readTree(jsonString);

    assertThat(jsonTree.size(), is(1));//  w w w.j a  va  2 s  .  c o  m
    assertThat(jsonTree.has("testEnum"), is(true));
    assertThat(jsonTree.get("testEnum").isIntegralNumber(), is(true));
    assertThat(jsonTree.get("testEnum").asInt(), is(1));
}

From source file:org.mybatis.spring.config.MapperScannerBeanDefinitionParser.java

/**
 * {@inheritDoc}/*from   ww  w.  j  a  v  a  2s. c o  m*/
 */
@Override
public synchronized BeanDefinition parse(Element element, ParserContext parserContext) {
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(parserContext.getRegistry());
    ClassLoader classLoader = scanner.getResourceLoader().getClassLoader();
    XmlReaderContext readerContext = parserContext.getReaderContext();
    scanner.setResourceLoader(readerContext.getResourceLoader());
    try {
        String annotationClassName = element.getAttribute(ATTRIBUTE_ANNOTATION);
        if (StringUtils.hasText(annotationClassName)) {
            @SuppressWarnings("unchecked")
            Class<? extends Annotation> markerInterface = (Class<? extends Annotation>) classLoader
                    .loadClass(annotationClassName);
            scanner.setAnnotationClass(markerInterface);
        }
        String markerInterfaceClassName = element.getAttribute(ATTRIBUTE_MARKER_INTERFACE);
        if (StringUtils.hasText(markerInterfaceClassName)) {
            Class<?> markerInterface = classLoader.loadClass(markerInterfaceClassName);
            scanner.setMarkerInterface(markerInterface);
        }
        String nameGeneratorClassName = element.getAttribute(ATTRIBUTE_NAME_GENERATOR);
        if (StringUtils.hasText(nameGeneratorClassName)) {
            Class<?> nameGeneratorClass = classLoader.loadClass(nameGeneratorClassName);
            BeanNameGenerator nameGenerator = BeanUtils.instantiateClass(nameGeneratorClass,
                    BeanNameGenerator.class);
            scanner.setBeanNameGenerator(nameGenerator);
        }
    } catch (Exception ex) {
        readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause());
    }
    String sqlSessionTemplateBeanName = element.getAttribute(ATTRIBUTE_TEMPLATE_REF);
    scanner.setSqlSessionTemplateBeanName(sqlSessionTemplateBeanName);
    String sqlSessionFactoryBeanName = element.getAttribute(ATTRIBUTE_FACTORY_REF);
    scanner.setSqlSessionFactoryBeanName(sqlSessionFactoryBeanName);
    scanner.registerFilters();
    String basePackage = element.getAttribute(ATTRIBUTE_BASE_PACKAGE);
    scanner.scan(StringUtils.tokenizeToStringArray(basePackage,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
    return null;
}

From source file:hermes.browser.dialog.HermesAdminFactoryConfigPanel.java

public void init() {
    final Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED);
    setLayout(new BorderLayout());
    setBorder(BorderFactory.createTitledBorder(border, ADMIN_FACTORY));

    afCombo.setModel(cfComboModel);//from  ww w  .  j av  a2 s  . c  om

    propertyTableSP.setViewportView(propertyTable);
    propertyTable.setSortable(true);
    add(afCombo, BorderLayout.NORTH);
    add(propertyTableSP, BorderLayout.CENTER);

    popupMenu.add(addItem);
    popupMenu.add(removeItem);

    addItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                propertyTableModel.insertRow();
            } catch (Exception ex) {
                cat.error(ex.getMessage(), ex);
            }
        }
    });

    removeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (propertyTable.getSelectedRow() != -1) {
                propertyTableModel.removeRow(propertyTable.getSelectedRow());
            }
        }
    });

    final MouseAdapter m = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)) {
                if (e.getComponent() == propertyTableSP) {
                    removeItem.setEnabled(false);
                } else {
                    removeItem.setEnabled(true);
                }

                if (propertySelectionComboBox.getModel().getSize() == 0) {
                    addItem.setEnabled(false);
                } else {
                    addItem.setEnabled(true);
                }

                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    };

    propertyTableSP.addMouseListener(m);
    propertyTable.addMouseListener(m);
    propertyTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

    cfComboModel.addListDataListener(new ListDataListener() {
        public void contentsChanged(ListDataEvent arg0) {
            final String className = HermesBrowser.getConfigDAO()
                    .getAdminClassForPlugIn((String) cfComboModel.getSelectedItem());
            final ClassLoaderManager classLoaderManager = (ClassLoaderManager) SingletonManager
                    .get(ClassLoaderManager.class);

            try {
                if (propertyTableModel != null) {
                    final ClassLoader classLoader = classLoaderManager
                            .getClassLoader(dialog.getSelectedLoader());
                    Thread.currentThread().setContextClassLoader(classLoader);

                    bean = (HermesAdminFactory) classLoader.loadClass(className).newInstance();
                    propertyTableModel.setBean(bean);
                    updateCellEditor();
                    dialog.setDirty();
                }
            } catch (Throwable e) {
                HermesBrowser.getBrowser().showErrorDialog(
                        "Unable to locate this plugin.\nSelect the loader the JMS provider classes are in before choosing the plugin.");
                cfComboModel.setSelectedItem(ConfigDAO.DEFAULT_PLUGIN);
            }
        }

        public void intervalAdded(ListDataEvent arg0) {
            // NOP
        }

        public void intervalRemoved(ListDataEvent arg0) {
            // NOP
        }
    });

}

From source file:com.quinsoft.zeidon.objectdefinition.ViewOd.java

private Object getConstraintObject(View view) {
    ObjectEngine oe = view.getObjectEngine();
    String className = getApplication().getPackage() + "." + getName() + "_Object";
    try {/*from   w w  w. j a v a 2s  .  c om*/
        ClassLoader classLoader = oe.getClassLoader(className);
        Class<?> operationsClass;
        operationsClass = classLoader.loadClass(className);
        try {
            // First try with View as the constructor args.
            Constructor<?> constructor = operationsClass.getConstructor(constructorArgTypes);
            return constructor.newInstance(view);
        } catch (NoSuchMethodException e) {
            try {
                // Maybe with a task constructor?
                Constructor<?> constructor = operationsClass.getConstructor(constructorArgTypes2);
                return constructor.newInstance(view.getTask());
            } catch (NoSuchMethodException e2) {
                // Now try with an empty constructor.
                Constructor<?> constructor = operationsClass.getConstructor();
                return constructor.newInstance();
            }
        }
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependViewOd(ViewOd.this)
                .appendMessage("Class name = %s", className)
                .appendMessage("See inner exception for more info.");
    }

}

From source file:azkaban.flowtrigger.plugin.FlowTriggerDependencyPluginManager.java

private DependencyCheck createDependencyCheck(final DependencyPluginConfig pluginConfig)
        throws FlowTriggerDependencyPluginException {
    final String classPath = pluginConfig.get(CLASS_PATH);

    final String[] cpList = classPath.split(",");

    final List<URL> resources = new ArrayList<>();

    try {/*from ww w.j  av a2s  . com*/
        for (final String cp : cpList) {
            final File[] files = getFilesMatchingPath(cp);
            if (files != null) {
                for (final File file : files) {
                    final URL cpItem = file.toURI().toURL();
                    if (!resources.contains(cpItem)) {
                        logger.info("adding to classpath " + cpItem);
                        resources.add(cpItem);
                    }
                }
            }
        }
    } catch (final Exception ex) {
        throw new FlowTriggerDependencyPluginException(ex);
    }

    final ClassLoader dependencyClassloader = new ParentLastURLClassLoader(
            resources.toArray(new URL[resources.size()]), this.getClass().getClassLoader());

    Thread.currentThread().setContextClassLoader(dependencyClassloader);

    Class<? extends DependencyCheck> clazz = null;
    try {
        clazz = (Class<? extends DependencyCheck>) dependencyClassloader
                .loadClass(pluginConfig.get(DEPENDENCY_CLASS));
        return (DependencyCheck) Utils.callConstructor(clazz);
    } catch (final Exception ex) {
        throw new FlowTriggerDependencyPluginException(ex);
    }
}