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:gr.demokritos.iit.textforms.TextForm.java

/**
 * Get an instance of the correct subclass - the subclass that can parse the
 * JSON. If an error is encountered it throws an exception like specified
 * below.//from   w  w  w. ja v a  2s. c  o m
 *
 * @param data, the data representing the text object
 * @param classname, the class - subclass of TextForm to use to parse
 * the format. Will cal fromFormat of that class.
 * @return An instance of the class that parses the JSON
 * @throws gr.demokritos.iit.textforms.TextForm.InvalidFormatException
 */
public static TextForm fromFormat(String data, Class classname) throws InvalidFormatException {
    try {
        Class<? extends TextForm> textform = classname.asSubclass(TextForm.class);
        Method fromFormat = textform.getMethod("fromFormat", String.class);
        return textform.cast(fromFormat.invoke(null, data));
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException ex) {
        if (!API.mapping.containsValue(classname)) {
            Logger.getLogger(TextForm.class.getName()).log(Level.SEVERE,
                    "fromFormat generics expects one of the " + "following values {0}",
                    API.mapping.values().toString());
        }
        Logger.getLogger(TextForm.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:de.tynne.benchmarksuite.Main.java

private static Map<BenchmarkSuite, BenchmarkProducer> getBenchmarkSuites()
        throws InstantiationException, IllegalAccessException {
    Reflections reflections = new Reflections("de.tynne.benchmarksuite");

    Set<Class<?>> benchmarkSuites = reflections.getTypesAnnotatedWith(BenchmarkSuite.class);

    Map<BenchmarkSuite, BenchmarkProducer> result = new HashMap<>();
    for (Class<?> clazz : benchmarkSuites) {
        BenchmarkSuite benchmarkSuite = clazz.getAnnotation(BenchmarkSuite.class);
        BenchmarkProducer benchmarkProducer = clazz.asSubclass(BenchmarkProducer.class).newInstance();
        result.put(benchmarkSuite, benchmarkProducer);
    }//from www .  ja  va2s  . c  o  m
    return result;
}

From source file:com.silverpeas.bootstrap.SilverpeasContextBootStrapper.java

/**
 * Loads all the JAR libraries available in the SILVERPEAS_HOME/repository/lib directory by using
 * our own classloader so that we avoid JBoss loads them with its its asshole VFS.
 *//* w  ww. j a  va  2  s . com*/
private static void loadExternalJarLibraries() {
    String libPath = System.getenv("SILVERPEAS_HOME") + separatorChar + "repository" + separatorChar + "lib";
    File libDir = new File(libPath);
    File[] jars = libDir.listFiles();
    URL[] jarURLs = new URL[jars.length];
    try {
        for (int i = 0; i < jars.length; i++) {
            jarURLs[i] = jars[i].toURI().toURL();
        }
        addURLs(jarURLs);
        String[] classNames = GeneralPropertiesManager.getString(CLASSES_TO_LOAD).split(",");
        for (String className : classNames) {
            try {
                Class aClass = ClassLoader.getSystemClassLoader().loadClass(className);
                Class<? extends Provider> jceProvider = aClass.asSubclass(Provider.class);
                Security.insertProviderAt(jceProvider.newInstance(), 0);
            } catch (Throwable t) {
                Logger.getLogger(SilverpeasContextBootStrapper.class.getSimpleName()).log(Level.SEVERE,
                        t.getMessage(), t);
            }
        }
    } catch (Exception ex) {
        Logger.getLogger(SilverpeasContextBootStrapper.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(),
                ex);
    }
}

From source file:com.asakusafw.testdriver.tools.runner.BatchTestTruncator.java

private static void resolveDescription(Conf conf, Class<?> description) {
    if (BatchDescription.class.isAssignableFrom(description)) {
        resolveBatch(conf, description.asSubclass(BatchDescription.class));
    } else if (FlowDescription.class.isAssignableFrom(description)) {
        resolveFlow(conf, description.asSubclass(FlowDescription.class));
    } else if (ImporterDescription.class.isAssignableFrom(description)) {
        resolveImporter(conf, description.asSubclass(ImporterDescription.class));
    } else if (ExporterDescription.class.isAssignableFrom(description)) {
        resolveExporter(conf, description.asSubclass(ExporterDescription.class));
    } else {/*  www. j  a v  a 2  s  .  co  m*/
        throw new IllegalArgumentException(
                MessageFormat.format(Messages.getString("BatchTestTruncator.errorInvalidTarget"), //$NON-NLS-1$
                        description.getName()));
    }
}

From source file:org.apache.synapse.config.xml.StartupFinder.java

private static void loadStartups() {
    // preregister any built in
    for (Class<?> builtin : builtins) {
        if (builtin != null) {
            Class<? extends StartupFactory> b = builtin.asSubclass(StartupFactory.class);
            StartupFactory sf;/*from  w  w  w.  j  a va 2s .  co  m*/
            try {
                sf = b.newInstance();
            } catch (Exception e) {
                throw new SynapseException("cannot instantiate " + b.getName(), e);

            }
            factoryMap.put(sf.getTagQName(), b);
            serializerMap.put(sf.getTagQName(), sf.getSerializerClass());
        }
    }
    registerExtensions();
    initialized = true;
}

From source file:org.apache.bookkeeper.util.ReflectionUtils.java

/**
 * Get the value of the <code>name</code> property as a <code>Class</code> implementing
 * the interface specified by <code>xface</code>.
 *
 * If no such property is specified, then <code>defaultValue</code> is returned.
 *
 * An exception is thrown if the returned class does not implement the named interface.
 *
 * @param conf/*from  w  w w.ja v  a2  s .c o  m*/
 *          Configuration Object.
 * @param name
 *          Class Property Name.
 * @param defaultValue
 *          Default Class to be returned.
 * @param xface
 *          The interface implemented by the named class.
 * @param classLoader
 *          Class Loader to load class.
 * @return property value as a <code>Class</code>, or <code>defaultValue</code>.
 * @throws ConfigurationException
 */
public static <U> Class<? extends U> getClass(Configuration conf, String name, Class<? extends U> defaultValue,
        Class<U> xface, ClassLoader classLoader) throws ConfigurationException {
    try {
        Class<?> theCls = getClass(conf, name, defaultValue, classLoader);
        if (null != theCls && !xface.isAssignableFrom(theCls)) {
            throw new ConfigurationException(theCls + " not " + xface.getName());
        } else if (null != theCls) {
            return theCls.asSubclass(xface);
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new ConfigurationException(e);
    }
}

From source file:org.apache.bookkeeper.common.util.ReflectionUtils.java

/**
 * Get the value of the <code>name</code> property as a <code>Class</code> implementing
 * the interface specified by <code>xface</code>.
 *
 * <p>If no such property is specified, then <code>defaultValue</code> is returned.
 *
 * <p>An exception is thrown if the returned class does not implement the named interface.
 *
 * @param conf// w w  w  . java 2 s . c om
 *          Configuration Object.
 * @param name
 *          Class Property Name.
 * @param defaultValue
 *          Default Class to be returned.
 * @param xface
 *          The interface implemented by the named class.
 * @param classLoader
 *          Class Loader to load class.
 * @return property value as a <code>Class</code>, or <code>defaultValue</code>.
 * @throws ConfigurationException
 */
public static <T> Class<? extends T> getClass(Configuration conf, String name, Class<? extends T> defaultValue,
        Class<T> xface, ClassLoader classLoader) throws ConfigurationException {
    try {
        Class<?> theCls = getClass(conf, name, defaultValue, classLoader);
        if (null != theCls && !xface.isAssignableFrom(theCls)) {
            throw new ConfigurationException(theCls + " not " + xface.getName());
        } else if (null != theCls) {
            return theCls.asSubclass(xface);
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new ConfigurationException(e);
    }
}

From source file:nl.tudelft.graphalytics.Graphalytics.java

private static Class<? extends Platform> getPlatformClassForName(String platformClassName) {
    // Load the class by name
    Class<? extends Platform> platformClass;
    try {/*from   w  w  w.  j  av a2s . co m*/
        Class<?> platformClassUncasted = Class.forName(platformClassName);
        if (!Platform.class.isAssignableFrom(platformClassUncasted)) {
            throw new GraphalyticsLoaderException("Expected class \"" + platformClassName
                    + "\" to be a subclass of \"nl.tudelft.graphalytics.Platform\".");
        }

        platformClass = platformClassUncasted.asSubclass(Platform.class);
    } catch (ClassNotFoundException e) {
        throw new GraphalyticsLoaderException("Could not find class \"" + platformClassName + "\".", e);
    }
    return platformClass;
}

From source file:net.solarnetwork.node.util.ClassUtils.java

/**
 * Load a class of a particular type.//from   w w w .j  a  v a 2 s. c  om
 * 
 * <p>
 * This uses the {@code type}'s ClassLoader to load the class. If that is
 * not available, it will use the current thread's context class loader.
 * </p>
 * 
 * @param <T>
 *        the desired interface type
 * @param className
 *        the class name that implements the interface
 * @param type
 *        the desired interface
 * @return the class
 */
public static <T> Class<? extends T> loadClass(String className, Class<T> type) {
    try {
        ClassLoader loader = type.getClassLoader();
        if (loader == null) {
            loader = Thread.currentThread().getContextClassLoader();
        }
        Class<?> clazz = loader.loadClass(className);
        if (!type.isAssignableFrom(clazz)) {
            throw new RuntimeException("Class [" + clazz + "] is not a [" + type + ']');
        }
        return clazz.asSubclass(type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Unable to load class [" + className + ']', e);
    }
}

From source file:org.apache.oozie.action.hadoop.LauncherMain.java

/**
 * Will run the user specified OozieActionConfigurator subclass (if one is provided) to update the action configuration.
 *
 * @param actionConf The action configuration to update
 * @throws OozieActionConfiguratorException
 *///from   w w  w . j a v a 2 s  .com
protected static void runConfigClass(JobConf actionConf) throws OozieActionConfiguratorException {
    String configClass = System.getProperty(LauncherMapper.OOZIE_ACTION_CONFIG_CLASS);
    if (configClass != null) {
        try {
            Class<?> klass = Class.forName(configClass);
            Class<? extends OozieActionConfigurator> actionConfiguratorKlass = klass
                    .asSubclass(OozieActionConfigurator.class);
            OozieActionConfigurator actionConfigurator = actionConfiguratorKlass.newInstance();
            actionConfigurator.configure(actionConf);
        } catch (ClassNotFoundException e) {
            throw new OozieActionConfiguratorException(
                    "An Exception occurred while instantiating the action config class", e);
        } catch (InstantiationException e) {
            throw new OozieActionConfiguratorException(
                    "An Exception occurred while instantiating the action config class", e);
        } catch (IllegalAccessException e) {
            throw new OozieActionConfiguratorException(
                    "An Exception occurred while instantiating the action config class", e);
        }
    }
}