Example usage for java.lang Class asSubclass

List of usage examples for java.lang Class asSubclass

Introduction

In this page you can find the example usage for java.lang Class asSubclass.

Prototype

@SuppressWarnings("unchecked")
public <U> Class<? extends U> asSubclass(Class<U> clazz) 

Source Link

Document

Casts this Class object to represent a subclass of the class represented by the specified class object.

Usage

From source file:com.github.ukase.toolkit.jar.JarSource.java

private Helper<?> getHelper(String className) {
    try {//from w ww . j  a va  2s  .  c o m
        Class<?> clazz = Class.forName(className, true, classLoader);
        Class<? extends Helper> helperClass = clazz.asSubclass(Helper.class);
        return helperClass.getConstructor().newInstance();
    } catch (ReflectiveOperationException e) {
        throw new IllegalStateException("Wrong configuration", e);
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.InMemoryConnectionServiceImpl.java

/**
 * NOTE: caller is responsible for closing connection
 *
 * @param ds//from   w  w  w .j  a  va2  s.  co  m
 * @return
 * @throws DataSourceManagementException
 */
private static java.sql.Connection getConnection(IDatabaseConnection connection)
        throws ConnectionServiceException {
    java.sql.Connection conn = null;

    String driverClass = connection.getAccessType().getClass().toString();
    if (StringUtils.isEmpty(driverClass)) {
        logger.error(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0020_CONNECTION_ATTEMPT_FAILED"));
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0020_CONNECTION_ATTEMPT_FAILED")); //$NON-NLS-1$

    }
    Class<?> driverC = null;

    try {
        driverC = Class.forName(driverClass);
    } catch (ClassNotFoundException e) {
        logger.error(Messages.getErrorString(
                "ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass), e);
        throw new ConnectionServiceException(Messages.getErrorString(
                "ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH"), e); //$NON-NLS-1$

    }
    if (!Driver.class.isAssignableFrom(driverC)) {
        logger.error(Messages.getErrorString(
                "ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass));
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH")); //$NON-NLS-1$

    }
    Driver driver = null;

    try {
        driver = driverC.asSubclass(Driver.class).newInstance();
    } catch (InstantiationException e) {
        logger.error(
                Messages.getErrorString(
                        "ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER", driverClass),
                e);
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER"), e); //$NON-NLS-1$
    } catch (IllegalAccessException e) {
        logger.error(
                Messages.getErrorString(
                        "ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER", driverClass),
                e);
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER"), e); //$NON-NLS-1$
    }
    try {
        DriverManager.registerDriver(driver);
        DatabaseDialectService dialectService = new DatabaseDialectService();
        IDatabaseDialect dialect = dialectService.getDialect(connection);

        conn = DriverManager.getConnection(dialect.getURLWithExtraOptions(connection), connection.getUsername(),
                connection.getPassword());
        return conn;
    } catch (SQLException e) {
        logger.error(Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"),
                e);
        throw new ConnectionServiceException(
                Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"), e); //$NON-NLS-1$
    } catch (DatabaseDialectException e) {
        logger.error(Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"),
                e);
        throw new ConnectionServiceException(
                Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"), e); //$NON-NLS-1$
    }
}

From source file:org.apache.apex.engine.plugin.loaders.PropertyBasedPluginLocator.java

@Override
public Set<T> discoverPlugins(Configuration conf) {
    Set<T> detectedPlugins = new LinkedHashSet<>();
    String classNamesStr = conf.get(this.propertyName);
    if (StringUtils.isBlank(classNamesStr)) {
        return detectedPlugins;
    }//from  w ww  .  ja  v  a  2  s .  c  o m

    Set<String> classNames = new LinkedHashSet<>();
    Collections.addAll(classNames, classNamesStr.split(","));
    for (String className : classNames) {
        try {
            Class<?> plugin = StramUtils.classForName(className, Object.class);
            if (klass.isAssignableFrom(plugin)) {
                detectedPlugins.add(StramUtils.newInstance(plugin.asSubclass(klass)));
            } else {
                LOG.info("Skipping loading {} incompatible with {}", className, klass);
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Could not load plugin {}", className, e);
        }
    }
    return detectedPlugins;
}

From source file:therian.module.SelfContainedTherianModule.java

private Operator<?>[] getSelfContainedOperators() {
    final List<Operator<?>> result = new ArrayList<>();

    for (Class<?> c : ClassUtils.hierarchy(getClass(), interfacesPolicy)) {
        for (Class<?> inner : c.getDeclaredClasses()) {
            if (Operator.class.isAssignableFrom(inner)) {
                final Operator<?> operator = newInstance(inner.asSubclass(Operator.class));
                if (operator != null) {
                    result.add(operator);
                }//from www  .j a  v a2s . com
            }
        }
    }
    return result.toArray(new Operator[result.size()]);
}

From source file:com.flozano.socialauth.AbstractProvider.java

@Override
public final void registerPlugins() throws Exception {
    LOG.info("Loading plugins");
    List<String> pluginsList = getPluginsList();
    if (pluginsList != null && !pluginsList.isEmpty()) {
        for (String s : pluginsList) {
            LOG.info("Loading plugin :: " + s);
            Class<? extends Plugin> clazz = Class.forName(s).asSubclass(Plugin.class);
            // getting constructor only for checking
            Constructor<? extends Plugin> cons = clazz.getConstructor(ProviderSupport.class);
            Class<?> interfaces[] = clazz.getInterfaces();
            for (Class<?> c : interfaces) {
                if (Plugin.class.isAssignableFrom(c)) {
                    pluginsMap.put(c.asSubclass(Plugin.class), clazz);
                }/*from w  ww  .j  av  a 2s  .  c  o  m*/
            }
        }
    }
}

From source file:org.stanwood.nwn2.gui.parser.BasicNWN2GUIParser.java

protected NWN2GUIObject createGUIObject(CommonTree node, NWN2GUIObject parent) throws GUIParseException {
    String name = getGUIObjectName(node);
    Map<String, String> attributes = getGUIObjectAttributes(node);

    String className = getObjectClassName(name);
    try {/*from  www.  j a  v  a 2  s  .co  m*/
        Class<?> c = Class.forName(className);
        Class<? extends NWN2GUIObject> guiObjectClass = c.asSubclass(NWN2GUIObject.class);
        Constructor<? extends NWN2GUIObject> constructor = guiObjectClass.getConstructor(NWN2GUIObject.class);
        NWN2GUIObject guiObject = constructor.newInstance(parent);
        setAttributes(guiObject, attributes);
        return guiObject;
    } catch (NoClassDefFoundError e) {
        throw new GUIParseException("Unable to find UIObject class : " + className, e);
    } catch (ClassNotFoundException e) {
        throw new GUIParseException("Unable to find UIObject class : " + className, e);
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.spoutcraft.api.addon.AddonLoader.java

public Addon load(Path path) throws InvalidAddonException, InvalidDescriptionException {
    final AddonDescription description = create(path);
    Addon addon = null;/* www  . jav a  2s  .  c  om*/
    AddonClassLoader loader;

    if (description.isValidMode(game.getSide())) {
        final Path dataPath = Paths.get(path.getParent().toString(), description.getIdentifier());
        try {
            loader = new AddonClassLoader(this.getClass().getClassLoader(), this);
            loader.addURL(path.toUri().toURL());
            Class<?> addonMain = Class.forName(description.getMain(), true, loader);
            Class<? extends Addon> addonClass = addonMain.asSubclass(Addon.class);
            Constructor<? extends Addon> constructor = addonClass.getConstructor();
            addon = constructor.newInstance();
            addon.initialize(game, this, description, loader, dataPath, path);
            addonMD5s.put(description.getIdentifier(), DigestUtils.md5Hex(new FileInputStream(path.toFile())));
        } catch (Exception e) {
            throw new InvalidAddonException(e);
        }
        loader.setAddon(addon);
        loaders.put(description.getIdentifier(), loader);
    }
    return addon;
}

From source file:cross.ObjectFactory.java

@Override
public <T> T instantiate(final String classname, final Class<T> cls) {
    EvalTools.notNull(classname, "Class name of type " + cls.getName() + " was null!", Factory.class);
    final Class<?> c = loadClass(classname);
    final Class<? extends T> t = c.asSubclass(cls);
    return instantiate(t);
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.utils.DatasourceInMemoryServiceHelper.java

/**
 * NOTE: caller is responsible for closing connection
 *
 * @param connectionName/* w  w w  .java2  s . c  o m*/
 * @return
 * @throws DatasourceServiceException
 */
public static java.sql.Connection getDataSourceConnection(String connectionName)
        throws DatasourceServiceException {
    IDatabaseConnection connection = null;
    try {
        ConnectionServiceImpl service = new ConnectionServiceImpl();
        connection = service.getConnectionByName(connectionName);
    } catch (ConnectionServiceException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Connection conn = null;

    DatabaseDialectService dialectService = new DatabaseDialectService();
    IDatabaseDialect dialect = dialectService.getDialect(connection);
    String driverClass = null;
    if (connection.getDatabaseType().getShortName().equals("GENERIC")) {
        driverClass = connection.getAttributes().get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS);
    } else {
        driverClass = dialect.getNativeDriver();
    }
    if (StringUtils.isEmpty(driverClass)) {
        logger.error(Messages
                .getErrorString("DatasourceInMemoryServiceHelper.ERROR_0001_CONNECTION_ATTEMPT_FAILED")); //$NON-NLS-1$
        throw new DatasourceServiceException(Messages
                .getErrorString("DatasourceInMemoryServiceHelper.ERROR_0001_CONNECTION_ATTEMPT_FAILED")); //$NON-NLS-1$
    }
    Class<?> driverC = null;

    try {
        driverC = Class.forName(driverClass);
    } catch (ClassNotFoundException e) {
        logger.error(Messages.getErrorString(
                "DatasourceInMemoryServiceHelper.ERROR_0002_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass), e); //$NON-NLS-1$
        throw new DatasourceServiceException(Messages
                .getErrorString("DatasourceInMemoryServiceHelper.ERROR_0002_DRIVER_NOT_FOUND_IN_CLASSPATH"), e); //$NON-NLS-1$
    }
    if (!Driver.class.isAssignableFrom(driverC)) {
        logger.error(Messages.getErrorString(
                "DatasourceInMemoryServiceHelper.ERROR_0002_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass)); //$NON-NLS-1$
        throw new DatasourceServiceException(Messages.getErrorString(
                "DatasourceInMemoryServiceHelper.ERROR_0002_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass)); //$NON-NLS-1$
    }
    Driver driver = null;

    try {
        driver = driverC.asSubclass(Driver.class).newInstance();
    } catch (InstantiationException e) {
        logger.error(Messages.getErrorString(
                "DatasourceInMemoryServiceHelper.ERROR_0003_UNABLE_TO_INSTANCE_DRIVER", driverClass), e); //$NON-NLS-1$
        throw new DatasourceServiceException(
                Messages.getErrorString("DatasourceInMemoryServiceHelper.ERROR_0003_UNABLE_TO_INSTANCE_DRIVER"),
                e); //$NON-NLS-1$
    } catch (IllegalAccessException e) {
        logger.error(Messages.getErrorString(
                "DatasourceInMemoryServiceHelper.ERROR_0003_UNABLE_TO_INSTANCE_DRIVER", driverClass), e); //$NON-NLS-1$
        throw new DatasourceServiceException(
                Messages.getErrorString("DatasourceInMemoryServiceHelper.ERROR_0003_UNABLE_TO_INSTANCE_DRIVER"),
                e); //$NON-NLS-1$
    }
    try {
        DriverManager.registerDriver(driver);
        conn = DriverManager.getConnection(dialect.getURLWithExtraOptions(connection), connection.getUsername(),
                connection.getPassword());
        return conn;
    } catch (SQLException e) {
        logger.error(Messages.getErrorString("DatasourceInMemoryServiceHelper.ERROR_0004_UNABLE_TO_CONNECT"),
                e); //$NON-NLS-1$
        throw new DatasourceServiceException(
                Messages.getErrorString("DatasourceInMemoryServiceHelper.ERROR_0004_UNABLE_TO_CONNECT"), e); //$NON-NLS-1$
    } catch (DatabaseDialectException e) {
        throw new DatasourceServiceException(
                Messages.getErrorString("DatasourceInMemoryServiceHelper.ERROR_0004_UNABLE_TO_CONNECT"), e); //$NON-NLS-1$
    }
}

From source file:org.solmix.runtime.support.spring.SpringBeanProvider.java

/**
 * {@inheritDoc}//from  w  ww  .j  av  a2 s  .c  o m
 * 
 * @see org.solmix.api.bean.ConfiguredBeanProvider#loadBeansOfType(java.lang.Class,
 *      org.solmix.api.bean.ConfiguredBeanProvider.BeanLoaderListener)
 */
@Override
public <T> boolean loadBeansOfType(Class<T> type, BeanLoaderListener<T> listener) {
    List<String> list = new ArrayList<String>(Arrays.asList(context.getBeanNamesForType(type, false, false)));
    list.removeAll(passThroughs);
    Collections.reverse(list);
    boolean loaded = false;
    for (String s : list) {
        Class<?> beanType = context.getType(s);
        Class<? extends T> t = beanType.asSubclass(type);
        if (listener.loadBean(s, t)) {
            Object o = context.getBean(s);
            if (listener.beanLoaded(s, type.cast(o))) {
                return true;
            }
            loaded = true;
        }
    }
    return loaded || original.loadBeansOfType(type, listener);
}