Example usage for java.lang Class getClass

List of usage examples for java.lang Class getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:edu.harvard.med.screensaver.io.CommandLineApplication.java

public <T extends Enum<T>> T getCommandLineOptionEnumValue(String optionName, Class<T> ofEnum) {
    verifyOptionsProcessed();//www. j av a  2  s.  c  o  m
    _lastAccessOption = _options.getOption(optionName);
    if (!_cmdLine.hasOption(optionName) && _option2DefaultValue.containsKey(optionName)) {
        return (T) _option2DefaultValue.get(optionName);
    }
    if (_cmdLine.hasOption(optionName)) {
        Object value = getCommandLineOptionValue(optionName);
        try {
            Enum<T> valueOf = Enum.valueOf(ofEnum, value.toString().toUpperCase());
            return (T) valueOf;
        } catch (Exception e) {
            showHelpAndExit("could not parse option " + optionName + " with arg " + value + " as enum "
                    + ofEnum.getClass().getSimpleName());
        }
    }
    return null;
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * Validate a Method to be a main command line application method.
 *
 * Methods with more than 1 argument are not allowed. Methods with return types
 * are not allowed. Methods that throw an exception other than
 * org.apache.commons.cli.CommandLineException are not allowed,
 *
 * @param method the method to validate//from   ww  w . j  a  va  2s.c om
 * @return A new method helper for the method
 */
private CommandLineMethodHelper getHelperForCommandLineMain(Method method) throws CommandLineException {

    // Validate that the return type is a void
    if (!method.getReturnType().equals(Void.TYPE)) {
        throw new CommandLineException("For method " + method.getName() + ", the return type is not void");
    }

    // Validate the exceptions throws by the method
    for (Class<?> clazz : method.getExceptionTypes()) {
        if (!clazz.equals(CommandLineException.class)) {
            throw new CommandLineException("For method " + method.getName()
                    + ", there is an invalid exception class " + clazz.getName());
        }
    }

    // In order to get ready to create the configuration instance,
    // we will need to know the command line option type
    // and the element type.
    Class<?> elementClass;
    MethodType methodType;
    Converter converter;

    // Get the parameters of the method. We'll use these to
    // determine what type of option we have - scalar, boolean, etc.
    Class<?> parameterClasses[] = method.getParameterTypes();

    // See what the length tells us
    switch (parameterClasses.length) {
    case 0:
        throw new CommandLineException("Main command line method must take arguments");
    case 1: {

        // For a method with one argument, we have to look
        // more closely at the argument. It has to be a simple
        // scalar object, an array, or a list.
        Class<?> parameterClass = parameterClasses[0];
        if (parameterClass.isArray()) {

            // For an array, we get the element class based on the
            // underlying component type
            methodType = MethodType.Array;
            elementClass = parameterClass.getComponentType();
        } else {

            // For a scalar, we get the element type from the
            // type of the parameter.
            methodType = MethodType.Scalar;
            elementClass = parameterClass.getClass();
        }

        // Now that we have the element type, make sure it's convertable
        converter = ConvertUtils.lookup(String.class, elementClass);
        if (converter == null) {
            throw new CommandLineException("Cannot find a conversion from String to " + elementClass.getName()
                    + " for method " + method.getName());
        }
        break;
    }
    default: {

        // Other method types not allowed.
        throw new CommandLineException("Method " + method.getName() + " has too many arguments");
    }
    }

    // Now we can return the configuration for this method
    return new CommandLineMethodHelper(method, methodType, elementClass, converter);
}

From source file:org.apereo.portal.groups.smartldap.SmartLdapGroupStore.java

public EntityIdentifier[] searchForGroups(String query, int method, Class leaftype) throws GroupsException {

    if (isTreeRefreshRequired()) {
        refreshTree();/*  w w  w.j  a va  2 s .  c o  m*/
    }

    log.debug("Invoking searchForGroups():  query={}, method={}, leaftype=", query, method,
            leaftype.getClass().getName());

    // We only match the IPerson leaf type...
    final IEntityGroup root = getRootGroup();
    if (!leaftype.equals(root.getLeafType())) {
        return new EntityIdentifier[0];
    }

    // We need to escape regex special characters that appear in the query string...
    final String[][] specials = new String[][] {
            /* backslash must come first! */
            new String[] { "\\", "\\\\" }, new String[] { "[", "\\[" },
            /* closing ']' isn't needed b/c it's a normal character w/o a preceding '[' */
            new String[] { "{", "\\{" },
            /* closing '}' isn't needed b/c it's a normal character w/o a preceding '{' */
            new String[] { "^", "\\^" }, new String[] { "$", "\\$" }, new String[] { ".", "\\." },
            new String[] { "|", "\\|" }, new String[] { "?", "\\?" }, new String[] { "*", "\\*" },
            new String[] { "+", "\\+" }, new String[] { "(", "\\(" }, new String[] { ")", "\\)" } };
    for (String[] s : specials) {
        query = query.replace(s[0], s[1]);
    }

    // Establish the regex pattern to match on...
    String regex;
    switch (method) {
    case IGroupConstants.IS:
        regex = query.toUpperCase();
        break;
    case IGroupConstants.STARTS_WITH:
        regex = query.toUpperCase() + ".*";
        break;
    case IGroupConstants.ENDS_WITH:
        regex = ".*" + query.toUpperCase();
        break;
    case IGroupConstants.CONTAINS:
        regex = ".*" + query.toUpperCase() + ".*";
        break;
    default:
        String msg = "Unsupported search method:  " + method;
        throw new GroupsException(msg);
    }

    List<EntityIdentifier> rslt = new LinkedList<>();
    for (Map.Entry<String, List<String>> y : groupsTree.getKeysByUpperCaseName().entrySet()) {
        if (y.getKey().matches(regex)) {
            List<String> keys = y.getValue();
            for (String k : keys) {
                rslt.add(new EntityIdentifier(k, IEntityGroup.class));
            }
        }
    }

    return rslt.toArray(new EntityIdentifier[rslt.size()]);

}

From source file:org.brekka.phalanx.client.services.impl.PhalanxServiceClient.java

@SuppressWarnings("unchecked")
protected <ReqDoc extends XmlObject, RespDoc extends XmlObject> RespDoc marshal(final ReqDoc requestDocument,
        final Class<RespDoc> expected) {
    Object marshalSendAndReceive;
    try {//from w  w  w.  j av  a 2 s  .co m
        marshalSendAndReceive = this.phalanxWebServiceOperations.marshalSendAndReceive(requestDocument);
    } catch (SoapFaultClientException e) {
        identifyFault(e);
        throw new PhalanxException(PhalanxErrorCode.CP500, e, "Request '%s' failed",
                requestDocument.schemaType().toString());
    }
    if (!expected.isAssignableFrom(marshalSendAndReceive.getClass())) {
        throw new PhalanxException(PhalanxErrorCode.CP500, "Expected '%s', actual '%s'",
                expected.getClass().getName(), marshalSendAndReceive.getClass().getName());
    }
    return (RespDoc) marshalSendAndReceive;
}

From source file:org.jasig.portal.groups.smartldap.SmartLdapGroupStore.java

public EntityIdentifier[] searchForGroups(String query, int method, Class leaftype) throws GroupsException {

    if (isTreeRefreshRequired()) {
        refreshTree();/*from  w ww  .j  a v a  2 s  .  com*/
    }

    if (log.isDebugEnabled()) {
        log.debug("Invoking searchForGroups():  query=" + query + ", method=" + method + ", leaftype="
                + leaftype.getClass().getName());
    }

    // We only match the IPerson leaf type...
    if (!leaftype.equals(ROOT_GROUP.getEntityType())) {
        return new EntityIdentifier[0];
    }

    // We need to escape regex special characters that appear in the query string...
    final String[][] specials = new String[][] {
            /* backslash must come first! */
            new String[] { "\\", "\\\\" }, new String[] { "[", "\\[" },
            /* closing ']' isn't needed b/c it's a normal character w/o a preceding '[' */
            new String[] { "{", "\\{" },
            /* closing '}' isn't needed b/c it's a normal character w/o a preceding '{' */
            new String[] { "^", "\\^" }, new String[] { "$", "\\$" }, new String[] { ".", "\\." },
            new String[] { "|", "\\|" }, new String[] { "?", "\\?" }, new String[] { "*", "\\*" },
            new String[] { "+", "\\+" }, new String[] { "(", "\\(" }, new String[] { ")", "\\)" } };
    for (String[] s : specials) {
        query = query.replace(s[0], s[1]);
    }

    // Establish the regex pattern to match on...
    String regex = null;
    switch (method) {
    case IGroupConstants.IS:
        regex = query.toUpperCase();
        break;
    case IGroupConstants.STARTS_WITH:
        regex = query.toUpperCase() + ".*";
        break;
    case IGroupConstants.ENDS_WITH:
        regex = ".*" + query.toUpperCase();
        break;
    case IGroupConstants.CONTAINS:
        regex = ".*" + query.toUpperCase() + ".*";
        break;
    default:
        String msg = "Unsupported search method:  " + method;
        throw new GroupsException(msg);
    }

    List<EntityIdentifier> rslt = new LinkedList<EntityIdentifier>();
    for (Map.Entry<String, List<String>> y : groupsTree.getKeysByUpperCaseName().entrySet()) {
        if (y.getKey().matches(regex)) {
            List<String> keys = y.getValue();
            for (String k : keys) {
                rslt.add(new EntityIdentifier(k, IEntityGroup.class));
            }
        }
    }

    return rslt.toArray(new EntityIdentifier[0]);

}

From source file:org.seedstack.seed.core.internal.CorePlugin.java

@SuppressWarnings("unchecked")
@Override/*from  www  .  ja  v  a2 s  .  c  o  m*/
public InitState init(InitContext initContext) {
    int failedUrlCount = FALLBACK_URL_TYPE.getFailedUrls().size();
    if (failedUrlCount > 0) {
        LOGGER.info("{} URL(s) were not scanned, enable debug logging to see them", failedUrlCount);
        if (LOGGER.isTraceEnabled()) {
            for (URL failedUrl : FALLBACK_URL_TYPE.getFailedUrls()) {
                LOGGER.debug("URL not scanned: {}", failedUrl);
            }
        }
    }

    Set<URL> scannedUrls = extractScannedUrls(initContext);
    if (scannedUrls != null) {
        DIAGNOSTIC_MANAGER.setClasspathUrls(scannedUrls);
    }

    Map<Class<? extends Annotation>, Collection<Class<?>>> scannedClassesByAnnotationClass = initContext
            .scannedClassesByAnnotationClass();
    Map<Class<?>, Collection<Class<?>>> scannedSubTypesByParentClass = initContext
            .scannedSubTypesByParentClass();

    for (Class<?> candidate : scannedSubTypesByParentClass.get(DiagnosticInfoCollector.class)) {
        if (DiagnosticInfoCollector.class.isAssignableFrom(candidate)) {
            DiagnosticDomain diagnosticDomain = candidate.getAnnotation(DiagnosticDomain.class);
            if (diagnosticDomain != null) {
                try {
                    diagnosticInfoCollectors.put(diagnosticDomain.value(),
                            (DiagnosticInfoCollector) candidate.newInstance());
                    LOGGER.trace("Detected diagnostic collector {} for diagnostic domain {}",
                            candidate.getCanonicalName(), diagnosticDomain.value());
                } catch (Exception e) {
                    throw SeedException.wrap(e, CoreErrorCode.UNABLE_TO_CREATE_DIAGNOSTIC_COLLECTOR)
                            .put("diagnosticCollectorClass", candidate.getClass().getCanonicalName());
                }
            }
        }
    }

    LOGGER.debug("Detected {} diagnostic collector(s)", diagnosticInfoCollectors.size());

    for (Class<?> candidate : scannedClassesByAnnotationClass.get(Install.class)) {
        if (Module.class.isAssignableFrom(candidate)) {
            seedModules.add(Module.class.getClass().cast(candidate));
            LOGGER.trace("Detected module to install {}", candidate.getCanonicalName());
        }
    }

    LOGGER.debug("Detected {} module(s) to install", seedModules.size());

    return InitState.INITIALIZED;
}

From source file:com.nridge.core.app.mgr.AppMgr.java

/**
 * Returns a logger instance matching the class parameter.  The
 * name associated with the class instance is used for the logger
 * identity.//w ww  .  j  a  va2 s .  c  o  m
 *
 * @param aClass Class instance to base identity on.
 *
 * @return An output logger instance.
 *
 * @see <a href="http://logback.qos.ch/">Logback Project</a>
 */
public Logger getLogger(Class<?> aClass) {
    return LoggerFactory.getLogger(aClass.getClass().getName());
}

From source file:org.lambdamatic.internal.elasticsearch.codec.DocumentCodec.java

/**
 * Converts the given {@code value} into a value of type {@code targetType}.
 * <p>//from  w  ww . jav a 2 s .com
 * <strong>Note:</strong>The conversion relies on the existence of a static
 * {@code valueOf(String)} method in the given {@code targetType} to convert the value.
 * </p>
 * 
 * @param value the input value
 * @param targetType the target type of the value to return
 * @return the converted value (or the value itself if no conversion was necessary)
 */
protected static Object convertValue(final Object value, final Class<?> targetType) {
    if (targetType.isAssignableFrom(value.getClass())) {
        return value;
    } else if (targetType.isPrimitive()) {
        if (targetType == boolean.class) {
            return Boolean.parseBoolean(value.toString());
        } else if (targetType == byte.class) {
            return Byte.parseByte(value.toString());
        } else if (targetType == short.class) {
            return Short.parseShort(value.toString());
        } else if (targetType == int.class) {
            return Integer.parseInt(value.toString());
        } else if (targetType == long.class) {
            return Long.parseLong(value.toString());
        } else if (targetType == double.class) {
            return Double.parseDouble(value.toString());
        } else if (targetType == float.class) {
            return Float.parseFloat(value.toString());
        }
        throw new CodecException("Failed to convert value '" + value.toString() + "' ("
                + value.getClass().getName() + ")  into a " + targetType.getName()
                + ": no object to primitive conversion available.");
    }
    try {
        final Method convertMethod = getConvertMethod(targetType);
        if (convertMethod != null) {
            return convertMethod.invoke(null, value.toString());
        }
        throw new CodecException(
                "Failed to convert value '" + value.toString() + "' (" + value.getClass().getName()
                        + ")  into a " + targetType.getName() + ": no conversion method available.");
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | SecurityException e) {
        throw new CodecException("Failed to convert value '" + value.toString() + "' ("
                + value.getClass().getName() + ") into a " + targetType.getClass().getName(), e);
    }
}

From source file:org.apache.axis.encoding.ser.BeanPropertyTarget.java

/**
 * set the bean property with specified value
 * @param value is the value./*ww  w  .j a va2s .com*/
 */
public void set(Object value) throws SAXException {

    try {
        // Set the value on the bean property. 
        // Use the indexed property method if the 
        // index is set.
        if (index < 0) {
            pd.set(object, value);
        } else {
            pd.set(object, index, value);
        }
    } catch (Exception e) {

        try {
            // If an exception occurred, 
            // see it the value can be converted into
            // the expected type.
            Class type = pd.getType();

            if (value.getClass().isArray() && value.getClass().getComponentType().isPrimitive()
                    && type.isArray() && type.getComponentType().equals(Object.class)) {
                //we make our own array type here.
                type = Array.newInstance(JavaUtils.getWrapperClass(value.getClass().getComponentType()), 0)
                        .getClass();
            }

            if (JavaUtils.isConvertable(value, type)) {
                value = JavaUtils.convert(value, type);
                if (index < 0)
                    pd.set(object, value);
                else
                    pd.set(object, index, value);
            } else {
                // It is possible that an indexed
                // format was expected, but the
                // entire array was sent.  In such 
                // cases traverse the array and 
                // call the setter for each item.
                if (index == 0 && value.getClass().isArray() && !type.getClass().isArray()) {
                    for (int i = 0; i < Array.getLength(value); i++) {
                        Object item = JavaUtils.convert(Array.get(value, i), type);
                        pd.set(object, i, item);
                    }
                } else {
                    // Can't proceed.  Throw an exception that
                    // will be caught in the catch block below.
                    throw e;
                }
            }
        } catch (Exception ex) {
            // Throw a SAX exception with an informative
            // message.
            String field = pd.getName();
            if (index >= 0) {
                field += "[" + index + "]";
            }
            if (log.isErrorEnabled()) {
                //TODO: why is this just logged on the server-side and not thrown back to the client???
                String valueType = "null";
                if (value != null)
                    valueType = value.getClass().getName();
                log.error(Messages.getMessage("cantConvert02", new String[] { valueType, field,
                        (index >= 0) ? pd.getType().getComponentType().getName() : pd.getType().getName() }));
            }
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t != null) {
                    String classname = this.object.getClass().getName();
                    //show the context where this exception occured.
                    throw new SAXException(Messages.getMessage("cantConvert04", new String[] { classname, field,
                            (value == null) ? null : value.toString(), t.getMessage() }));
                }
            }
            throw new SAXException(ex);
        }
    }
}

From source file:com.wabacus.system.assistant.ReportAssistant.java

public AbsReportDataPojo getPojoClassInstance(ReportRequest rrequest, ReportBean rbean, Class pojoClassObj) {
    try {//from w w  w .j  a  v a  2 s  .  com
        if (pojoClassObj == null)
            return null;
        return (AbsReportDataPojo) pojoClassObj
                .getConstructor(new Class[] { ReportRequest.class, ReportBean.class })
                .newInstance(new Object[] { rrequest, rbean });
    } catch (Exception e) {
        throw new WabacusRuntimeException("" + rbean.getPath() + "?"
                + pojoClassObj.getClass().getName() + "", e);
    }
}