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:Main.java

public static void main(String[] args) throws Exception {

    Main cls = new Main();
    Main subcls = new SubClass1();

    // class Main
    Class c = cls.getClass();/*from  www.j  av a2 s. co  m*/
    System.out.println(c);

    // sub class SubClass1
    Class c1 = subcls.getClass();
    System.out.println(c1);

    // represent a subclass of the specified class object
    Class retval = c1.asSubclass(c);

    System.out.println(retval);

}

From source file:eu.itesla_project.online.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {//from  w  w w  .ja va 2 s . co  m
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        String mode = line.getOptionValue("m");
        Path tmpDir = Paths.get(line.getOptionValue("t"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("f"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("s"));
        String statisticsDbName = line.getOptionValue("d");
        int coresPerRank = Integer.parseInt(line.getOptionValue("n"));
        Path stdOutArchive = line.hasOption("o") ? Paths.get(line.getOptionValue("o")) : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService executorService = MultiStateNetworkAwareExecutors.newCachedThreadPool();
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName);
            try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                    mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                OnlineConfig config = OnlineConfig.load();
                try (LocalOnlineApplication application = new LocalOnlineApplication(config, computationManager,
                        scheduledExecutorService, executorService, true)) {
                    switch (mode) {
                    case "ui":
                        System.out.println("LocalOnlineApplication created");
                        System.out.println("Waiting till shutdown");
                        // indefinitely wait for JMX commands
                        //TimeUnit.DAYS.sleep(Integer.MAX_VALUE);
                        synchronized (application) {
                            try {
                                application.wait();
                            } catch (InterruptedException ex) {
                            }

                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Invalid mode " + mode);
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
            executorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:eu.itesla_project.offline.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {/* w  w  w . j av  a  2 s .  c  om*/
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        Mode mode = Mode.valueOf(line.getOptionValue("mode"));
        String simulationDbName = line.hasOption("simulation-db-name")
                ? line.getOptionValue("simulation-db-name")
                : OfflineConfig.DEFAULT_SIMULATION_DB_NAME;
        String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name")
                : OfflineConfig.DEFAULT_RULES_DB_NAME;
        String metricsDbName = line.hasOption("metrics-db-name") ? line.getOptionValue("metrics-db-name")
                : OfflineConfig.DEFAULT_METRICS_DB_NAME;
        Path tmpDir = Paths.get(line.getOptionValue("tmp-dir"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("statistics-factory-class"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("statistics-db-dir"));
        String statisticsDbName = line.getOptionValue("statistics-db-name");
        int coresPerRank = Integer.parseInt(line.getOptionValue("cores"));
        Path stdOutArchive = line.hasOption("stdout-archive") ? Paths.get(line.getOptionValue("stdout-archive"))
                : null;
        String workflowId = line.hasOption("workflow") ? line.getOptionValue("workflow") : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService offlineExecutorService = MultiStateNetworkAwareExecutors
                .newSizeLimitedThreadPool("OFFLINE_POOL", 100);
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            try (MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName)) {
                try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                        mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                    OfflineConfig config = OfflineConfig.load();
                    try (LocalOfflineApplication application = new LocalOfflineApplication(config,
                            computationManager, simulationDbName, rulesDbName, metricsDbName,
                            scheduledExecutorService, offlineExecutorService)) {
                        switch (mode) {
                        case ui:
                            application.await();
                            break;

                        case simulations: {
                            if (workflowId == null) {
                                workflowId = application.createWorkflow(null,
                                        OfflineWorkflowCreationParameters.load());
                            }
                            application.startWorkflowAndWait(workflowId, OfflineWorkflowStartParameters.load());
                        }
                            break;

                        case rules: {
                            if (workflowId == null) {
                                throw new RuntimeException("Workflow '" + workflowId + "' not found");
                            }
                            application.computeSecurityRulesAndWait(workflowId);
                        }
                            break;

                        default:
                            throw new IllegalArgumentException("Invalid mode " + mode);
                        }
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            offlineExecutorService.shutdown();
            scheduledExecutorService.shutdown();
            offlineExecutorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:Main.java

public static Enum<?> newEnum(Class<?> enumClass, String enumStr) {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    Enum en = Enum.valueOf(enumClass.asSubclass(Enum.class), enumStr);
    return en;/*from   ww  w.ja v  a2s .c  om*/
}

From source file:org.jbpm.jpdl.internal.convert.node.NodeConverterTypes.java

static Map<String, Class<? extends Node>> initialiseNodeTypes() {
    Map<String, Class<? extends Node>> types = new HashMap<String, Class<? extends Node>>();
    InputStream nodeTypesStream = NodeConverterTypes.class.getClassLoader()
            .getResourceAsStream("node.converter.types.xml");
    Element nodeTypesElement = null;
    try {/*from w  w  w  . j  a v a2 s. co  m*/
        nodeTypesElement = reader.read(nodeTypesStream).getRootElement();
    } catch (DocumentException e1) {
        log.error("Failed to parse the node.converter.types.xml", e1);
    }
    Iterator<?> nodeTypeIterator = nodeTypesElement.elementIterator("node-type");
    while (nodeTypeIterator.hasNext()) {
        Element nodeTypeElement = (Element) nodeTypeIterator.next();

        String elementTag = nodeTypeElement.attributeValue("element");
        String className = nodeTypeElement.attributeValue("class");
        try {
            Class<?> nodeClass = NodeConverterTypes.class.forName(className);
            types.put(elementTag, nodeClass.asSubclass(Node.class));

        } catch (Exception e) {
            if (!"org.jboss.seam.jbpm.Page".equals(className)) {
                if (log.isDebugEnabled()) {
                    log.debug("node '" + elementTag + "' will not be available. class '" + className
                            + "' couldn't be loaded");
                }
            }
        }
    }

    return types;
}

From source file:org.jbpm.jpdl.internal.convert.action.ActionConverterTypes.java

static Map<String, Class<? extends Action>> initialiseActionTypes() {
    Map<String, Class<? extends Action>> types = new HashMap<String, Class<? extends Action>>();

    InputStream actionTypesStream = ActionConverterTypes.class.getClassLoader()
            .getResourceAsStream("action.converter.types.xml");

    Element actionTypesElement = null;
    try {//from  w  w w . ja va2s.co  m
        actionTypesElement = reader.read(actionTypesStream).getRootElement();
    } catch (DocumentException e1) {
        log.error("Failed to parse the action.converter.types.xml", e1);
    }

    Iterator<?> actionTypeIterator = actionTypesElement.elementIterator("action-type");
    while (actionTypeIterator.hasNext()) {
        Element actionTypeElement = (Element) actionTypeIterator.next();

        String elementTag = actionTypeElement.attributeValue("element");
        String className = actionTypeElement.attributeValue("class");
        try {
            Class<?> actionClass = ActionConverterTypes.class.forName(className);
            types.put(elementTag, actionClass.asSubclass(Action.class));

        } catch (Exception e) {
            // NOTE that Error's are not caught because that might halt the
            // JVM and mask the original Error.
            if (log.isDebugEnabled()) {
                log.debug("action '" + elementTag + "' will not be available. class '" + className
                        + "' couldn't be loaded");
            }
        }
    }
    return types;
}

From source file:org.kuali.rice.core.api.util.ClassLoaderUtils.java

public static <T> Class<? extends T> getClass(String className, Class<T> type) throws ClassNotFoundException {
    Class<?> theClass = ClassUtils.getClass(getDefaultClassLoader(), className);
    return theClass.asSubclass(type);
}

From source file:org.pentaho.pms.mql.MQLQueryFactory.java

public static MQLQuery getMQLQuery(String mqlQueryClassName, String XML, DatabaseMeta meta, String locale,
        CwmSchemaFactoryInterface factory) throws PentahoMetadataException {
    // load MQLQuery class instance from properties somewhere
    try {/*  w  w  w.  ja v  a2s  .  co  m*/
        Class<?> claz = Class.forName(mqlQueryClassName);

        Class<? extends MQLQuery> clazz = (Class<? extends MQLQuery>) claz.asSubclass(MQLQuery.class);

        if (MQLQuery.class.isAssignableFrom(clazz)) {
            Class[] argClasses = { String.class, DatabaseMeta.class, String.class,
                    CwmSchemaFactoryInterface.class };
            Constructor<? extends MQLQuery> constr = clazz.getConstructor(argClasses);
            Object[] vars = { XML, meta, locale, factory };
            return constr.newInstance(vars);
        } else {
            logger.error(Messages.getErrorString("MQLQueryFactory.ERROR_0001_MQLQUERY_CLASS_NOT_ASSIGNABLE", //$NON-NLS-1$
                    mqlQueryClassName));
        }
    } catch (ClassNotFoundException e) {
        logger.error(Messages.getErrorString("MQLQueryFactory.ERROR_0002_MQLQUERY_CLASS_NOT_FOUND", //$NON-NLS-1$
                mqlQueryClassName), e);
    } catch (NoSuchMethodException e) {
        logger.error(Messages.getErrorString(
                "MQLQueryFactory.ERROR_0003_MQLQUERY_CLASS_DOES_NOT_CONTAIN_CONSTRUCTOR", mqlQueryClassName), //$NON-NLS-1$
                e);
    } catch (IllegalAccessException e) {
        logger.error(Messages.getErrorString("MQLQueryFactory.ERROR_0004_MQLQUERY_CLASS_ILLEGAL_ACCESS", //$NON-NLS-1$
                mqlQueryClassName), e);
    } catch (InstantiationException e) {
        logger.error(Messages.getErrorString("MQLQueryFactory.ERROR_0005_MQLQUERY_CLASS_CANNOT_INSTANTIATE", //$NON-NLS-1$
                mqlQueryClassName), e);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof PentahoMetadataException) {
            throw (PentahoMetadataException) e.getTargetException();
        } else {
            logger.error(Messages.getErrorString("MQLQueryFactory.ERROR_0006_MQLQUERY_CLASS_CANNOT_INVOKE", //$NON-NLS-1$
                    mqlQueryClassName), e);
        }
    }
    return null;
}

From source file:therian.Operation.java

private static boolean init(Class<?> type) {
    final boolean valid;
    synchronized (type) {
        if (VALID_INFO.containsKey(type)) {
            valid = VALID_INFO.get(type).booleanValue();
        } else if (Modifier.isAbstract(type.getModifiers())) {
            valid = true;/* www . j a v  a  2  s . c  om*/
        } else {
            final Type resultType = TypeUtils.unrollVariables(TypeUtils.getTypeArguments(type, Operation.class),
                    TYPE_VARIABLE_RESULT);
            valid = !TypeUtils.containsTypeVariables(resultType);
            Validate.isTrue(valid, "%s does not fully bind type parameter %s from %s", type,
                    TYPE_VARIABLE_RESULT.getName(), Operation.class);
            VALID_INFO.put(type, Boolean.valueOf(valid));
        }
    }

    final Class<?> parent = type.getSuperclass();
    if (!Operation.class.equals(parent)) {
        init(parent.asSubclass(Operation.class));
    }
    return valid;
}

From source file:com.baidu.rigel.biplatform.parser.RegisterFunction.java

/** 
 * register/*  w  w w.j a  va  2 s.c  om*/
 * @param functionName
 * @param funClass
 * @return
 * @throws RegisterFunctionException
 */
public static boolean register(String functionName, Class<?> funClass) throws RegisterFunctionException {
    try {
        // get array constructor
        functionNames.put(functionName.toLowerCase(), funClass.asSubclass(FunctionNode.class).getConstructor());
    } catch (NoSuchMethodException | SecurityException e) {
        LOG.error("Register function:{} by class:{} catch error,error message:{}", functionName, funClass,
                e.getMessage());
        throw new RegisterFunctionException(functionName, funClass.getName(), e.getMessage());
    }

    return true;
}