Example usage for java.lang Class getModifiers

List of usage examples for java.lang Class getModifiers

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native int getModifiers();

Source Link

Document

Returns the Java language modifiers for this class or interface, encoded in an integer.

Usage

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();//from w  w  w  .  j a  v  a2 s  .  co  m
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

From source file:com.evolveum.midpoint.prism.marshaller.BeanUnmarshaller.java

private <T> T instantiateWithSubtypeGuess(@NotNull Class<T> beanClass, Collection<QName> fields)
        throws SchemaException {
    if (!Modifier.isAbstract(beanClass.getModifiers())) {
        return instantiate(beanClass); // non-abstract classes are currently instantiated directly (could be changed)
    }/* w  w  w .  jav  a2 s .  c o m*/
    Class<? extends T> subclass = inspector.findMatchingSubclass(beanClass, fields);
    return instantiate(subclass);
}

From source file:ca.uhn.fhir.parser.BaseParser.java

@SuppressWarnings("unchecked")
ChildNameAndDef getChildNameAndDef(BaseRuntimeChildDefinition theChild, IBase theValue) {
    Class<? extends IBase> type = theValue.getClass();
    String childName = theChild.getChildNameByDatatype(type);
    BaseRuntimeElementDefinition<?> childDef = theChild.getChildElementDefinitionByDatatype(type);
    if (childDef == null) {
        // if (theValue instanceof IBaseExtension) {
        // return null;
        // }//w  ww . j av  a 2s.  c  om

        /*
         * For RI structures Enumeration class, this replaces the child def
         * with the "code" one. This is messy, and presumably there is a better
         * way..
         */
        BaseRuntimeElementDefinition<?> elementDef = myContext.getElementDefinition(type);
        if (elementDef.getName().equals("code")) {
            Class<? extends IBase> type2 = myContext.getElementDefinition("code").getImplementingClass();
            childDef = theChild.getChildElementDefinitionByDatatype(type2);
            childName = theChild.getChildNameByDatatype(type2);
        }

        // See possibly the user has extended a built-in type without
        // declaring it anywhere, as in XmlParserDstu3Test#testEncodeUndeclaredBlock
        if (childDef == null) {
            Class<?> nextSuperType = theValue.getClass();
            while (IBase.class.isAssignableFrom(nextSuperType) && childDef == null) {
                if (Modifier.isAbstract(nextSuperType.getModifiers()) == false) {
                    BaseRuntimeElementDefinition<?> def = myContext
                            .getElementDefinition((Class<? extends IBase>) nextSuperType);
                    Class<?> nextChildType = def.getImplementingClass();
                    childDef = theChild
                            .getChildElementDefinitionByDatatype((Class<? extends IBase>) nextChildType);
                    childName = theChild.getChildNameByDatatype((Class<? extends IBase>) nextChildType);
                }
                nextSuperType = nextSuperType.getSuperclass();
            }
        }

        if (childDef == null) {
            throwExceptionForUnknownChildType(theChild, type);
        }
    }

    return new ChildNameAndDef(childName, childDef);
}

From source file:ca.uhn.fhir.rest.method.BaseResourceReturningMethodBinding.java

@SuppressWarnings("unchecked")
public BaseResourceReturningMethodBinding(Class<?> theReturnResourceType, Method theMethod,
        FhirContext theContext, Object theProvider) {
    super(theMethod, theContext, theProvider);

    Class<?> methodReturnType = theMethod.getReturnType();
    if (Collection.class.isAssignableFrom(methodReturnType)) {

        myMethodReturnType = MethodReturnTypeEnum.LIST_OF_RESOURCES;
        Class<?> collectionType = ReflectionUtil.getGenericCollectionTypeOfMethodReturnType(theMethod);
        if (collectionType != null) {
            if (!Object.class.equals(collectionType) && !IBaseResource.class.isAssignableFrom(collectionType)) {
                throw new ConfigurationException(
                        "Method " + theMethod.getDeclaringClass().getSimpleName() + "#" + theMethod.getName()
                                + " returns an invalid collection generic type: " + collectionType);
            }/*from  w w w . j  av a  2  s.co  m*/
        }
        myResourceListCollectionType = collectionType;

    } else if (IBaseResource.class.isAssignableFrom(methodReturnType)) {
        if (Modifier.isAbstract(methodReturnType.getModifiers()) == false && theContext
                .getResourceDefinition((Class<? extends IBaseResource>) methodReturnType).isBundle()) {
            myMethodReturnType = MethodReturnTypeEnum.BUNDLE_RESOURCE;
        } else {
            myMethodReturnType = MethodReturnTypeEnum.RESOURCE;
        }
    } else if (Bundle.class.isAssignableFrom(methodReturnType)) {
        myMethodReturnType = MethodReturnTypeEnum.BUNDLE;
    } else if (IBundleProvider.class.isAssignableFrom(methodReturnType)) {
        myMethodReturnType = MethodReturnTypeEnum.BUNDLE_PROVIDER;
    } else if (MethodOutcome.class.isAssignableFrom(methodReturnType)) {
        myMethodReturnType = MethodReturnTypeEnum.METHOD_OUTCOME;
    } else {
        throw new ConfigurationException("Invalid return type '" + methodReturnType.getCanonicalName()
                + "' on method '" + theMethod.getName() + "' on type: "
                + theMethod.getDeclaringClass().getCanonicalName());
    }

    if (theReturnResourceType != null) {
        if (IBaseResource.class.isAssignableFrom(theReturnResourceType)) {
            if (Modifier.isAbstract(theReturnResourceType.getModifiers())
                    || Modifier.isInterface(theReturnResourceType.getModifiers())) {
                // If we're returning an abstract type, that's ok
            } else {
                myResourceType = (Class<? extends IResource>) theReturnResourceType;
                myResourceName = theContext.getResourceDefinition(myResourceType).getName();
            }
        }
    }

    myPreferTypesList = createPreferTypesList();
}

From source file:com.comtop.cap.bm.metadata.common.dwr.CapMapConverter.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
    if (data.isNull()) {
        return null;
    }/*from  w  ww.  ja  v a 2s. co m*/

    String value = data.getValue();

    // If the text is null then the whole bean is null
    if (value.trim().equals(ProtocolConstants.INBOUND_NULL)) {
        return null;
    }

    if (!value.startsWith(ProtocolConstants.INBOUND_MAP_START)
            || !value.endsWith(ProtocolConstants.INBOUND_MAP_END)) {
        log.warn("Expected object while converting data for " + paramType.getName() + " in "
                + data.getContext().getCurrentProperty() + ". Passed: " + value);
        throw new ConversionException(paramType, "Data conversion error. See logs for more details.");
    }

    value = value.substring(1, value.length() - 1);

    try {
        // Maybe we ought to check that the paramType isn't expecting a more
        // distinct type of Map and attempt to create that?
        Map<Object, Object> map;

        // If paramType is concrete then just use whatever we've got.
        if (!paramType.isInterface() && !Modifier.isAbstract(paramType.getModifiers())) {
            // If there is a problem creating the type then we have no way
            // of completing this - they asked for a specific type and we
            // can't create that type. I don't know of a way of finding
            // subclasses that might be instaniable so we accept failure.
            map = (Map<Object, Object>) paramType.newInstance();
        } else {
            map = new HashMap<Object, Object>();
        }

        // Get the extra type info
        Property parent = data.getContext().getCurrentProperty();

        Property keyProp = parent.createChild(0);
        keyProp = converterManager.checkOverride(keyProp);

        Property valProp = parent.createChild(1);
        valProp = converterManager.checkOverride(valProp);

        // We should put the new object into the working map in case it
        // is referenced later nested down in the conversion process.
        data.getContext().addConverted(data, paramType, map);
        InboundContext incx = data.getContext();

        // Loop through the property declarations
        StringTokenizer st = new StringTokenizer(value, ",");
        int size = st.countTokens();
        for (int i = 0; i < size; i++) {
            String token = st.nextToken();
            if (token.trim().length() == 0) {
                continue;
            }

            int colonpos = token.indexOf(ProtocolConstants.INBOUND_MAP_ENTRY);
            if (colonpos == -1) {
                throw new ConversionException(paramType, "Missing " + ProtocolConstants.INBOUND_MAP_ENTRY
                        + " in object description: {1}" + token);
            }

            String valStr = token.substring(colonpos + 1).trim();
            String[] splitIv = ConvertUtil.splitInbound(valStr);
            String splitIvValue = splitIv[ConvertUtil.INBOUND_INDEX_VALUE];
            String splitIvType = splitIv[ConvertUtil.INBOUND_INDEX_TYPE];
            InboundVariable valIv = new InboundVariable(incx, null, splitIvType, splitIvValue);
            valIv.dereference();

            Class valTyClass = String.class;

            if ("boolean".equals(valIv.getType())) {
                valTyClass = Boolean.class;
            } else if ("array".equals(valIv.getType())) {
                valTyClass = ArrayList.class;
            } else if ("number".equals(valIv.getType())) {
                String strValue = valIv.getValue();
                if (strValue.indexOf(".") != -1) {
                    valTyClass = Double.class;
                } else {
                    valTyClass = Integer.class;
                }
            } else if ("date".equals(valIv.getType())) {
                valTyClass = Date.class;
            }

            Object val = converterManager.convertInbound(valTyClass, valIv, valProp);
            String keyStr = token.substring(0, colonpos).trim();
            map.put(keyStr, val);
        }

        return map;
    } catch (ConversionException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ConversionException(paramType, ex);
    }
}

From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

@Override
@SuppressWarnings("unchecked")
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype,
        ArgumentMatches matches) {//w  w  w  .  java 2s. c  o m
    Class type = makeRawTypeIfNecessary(fulltype);
    Type componentType;
    Object result;

    if (Collection.class.isAssignableFrom(type)) {

        // If this is a generic interface, pick a concrete implementation to create and pass back.
        // Because of type erasure, don't worry about creating one of exactly the correct type.
        if (Modifier.isInterface(type.getModifiers()) || Modifier.isAbstract(type.getModifiers())) {
            if (java.util.List.class.isAssignableFrom(type))
                type = ArrayList.class;
            else if (java.util.Queue.class.isAssignableFrom(type))
                type = java.util.ArrayDeque.class;
            else if (java.util.Set.class.isAssignableFrom(type))
                type = java.util.TreeSet.class;
        }

        componentType = getCollectionComponentType(source.field);
        ArgumentTypeDescriptor componentArgumentParser = parsingEngine
                .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));

        Collection collection;
        try {
            collection = (Collection) type.newInstance();
        } catch (InstantiationException e) {
            logger.fatal(
                    "ArgumentParser: InstantiationException: cannot convert field " + source.field.getName());
            throw new ReviewedStingException(
                    "constructFromString:InstantiationException: Failed conversion " + e.getMessage());
        } catch (IllegalAccessException e) {
            logger.fatal(
                    "ArgumentParser: IllegalAccessException: cannot convert field " + source.field.getName());
            throw new ReviewedStingException(
                    "constructFromString:IllegalAccessException: Failed conversion " + e.getMessage());
        }

        for (ArgumentMatch match : matches) {
            for (ArgumentMatch value : match) {
                Object object = componentArgumentParser.parse(parsingEngine, source, componentType,
                        new ArgumentMatches(value));
                collection.add(object);
                // WARNING: Side effect!
                parsingEngine.addTags(object, value.tags);
            }
        }

        result = collection;

    } else if (type.isArray()) {
        componentType = type.getComponentType();
        ArgumentTypeDescriptor componentArgumentParser = parsingEngine
                .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));

        // Assemble a collection of individual values used in this computation.
        Collection<ArgumentMatch> values = new ArrayList<ArgumentMatch>();
        for (ArgumentMatch match : matches)
            for (ArgumentMatch value : match)
                values.add(value);

        result = Array.newInstance(makeRawTypeIfNecessary(componentType), values.size());

        int i = 0;
        for (ArgumentMatch value : values) {
            Object object = componentArgumentParser.parse(parsingEngine, source, componentType,
                    new ArgumentMatches(value));
            Array.set(result, i++, object);
            // WARNING: Side effect!
            parsingEngine.addTags(object, value.tags);
        }
    } else
        throw new ReviewedStingException("Unsupported compound argument type: " + type);

    return result;
}

From source file:org.structr.module.JarConfigurationProvider.java

private void importResource(Module module) throws IOException {

    final Set<String> classes = module.getClasses();

    for (final String name : classes) {

        String className = StringUtils.removeStart(name, ".");

        logger.log(Level.FINE, "Instantiating class {0} ", className);

        try {/*from  w  w  w .  j a  v  a 2 s.  co m*/

            // instantiate class..
            Class clazz = Class.forName(className);
            int modifiers = clazz.getModifiers();

            logger.log(Level.FINE, "Class {0} instantiated: {1}", new Object[] { className, clazz });

            // register node entity classes
            if (NodeInterface.class.isAssignableFrom(clazz)) {

                registerEntityType(clazz);
            }

            // register entity classes
            if (AbstractRelationship.class.isAssignableFrom(clazz) && !(Modifier.isAbstract(modifiers))) {

                registerEntityType(clazz);
            }

            // register services
            if (Service.class.isAssignableFrom(clazz) && !(Modifier.isAbstract(modifiers))) {

                Services.getInstance().registerServiceClass(clazz);
            }

            // register agents
            if (Agent.class.isAssignableFrom(clazz) && !(Modifier.isAbstract(modifiers))) {

                String simpleName = clazz.getSimpleName();
                String fullName = clazz.getName();

                agentClassCache.put(simpleName, clazz);
                agentPackages.add(fullName.substring(0, fullName.lastIndexOf(".")));

            }

        } catch (Throwable t) {
        }

    }

}

From source file:org.metaworks.dwr.MetaworksMapConverter.java

@SuppressWarnings("unchecked")
public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
    if (data.isNull()) {
        return null;
    }/*from w  w  w  .j a v a 2  s. c  o m*/

    String value = data.getValue();

    // If the text is null then the whole bean is null
    if (value.trim().equals(ProtocolConstants.INBOUND_NULL)) {
        return null;
    }

    if (!value.startsWith(ProtocolConstants.INBOUND_MAP_START)
            || !value.endsWith(ProtocolConstants.INBOUND_MAP_END)) {
        log.warn("Expected object while converting data for " + paramType.getName() + " in "
                + data.getContext().getCurrentProperty() + ". Passed: " + value);
        throw new ConversionException(paramType, "Data conversion error. See logs for more details.");
    }

    value = value.substring(1, value.length() - 1);

    try {
        // Maybe we ought to check that the paramType isn't expecting a more
        // distinct type of Map and attempt to create that?
        Map<Object, Object> map;

        // If paramType is concrete then just use whatever we've got.
        if (!paramType.isInterface() && !Modifier.isAbstract(paramType.getModifiers())) {
            // If there is a problem creating the type then we have no way
            // of completing this - they asked for a specific type and we
            // can't create that type. I don't know of a way of finding
            // subclasses that might be instaniable so we accept failure.
            map = (Map<Object, Object>) paramType.newInstance();
        } else {
            map = new HashMap<Object, Object>();
        }

        // Get the extra type info
        Property parent = data.getContext().getCurrentProperty();

        Property keyProp = parent.createChild(0);
        keyProp = converterManager.checkOverride(keyProp);
        Class<?> keyType = keyProp.getPropertyType();

        Property valProp = parent.createChild(1);
        valProp = converterManager.checkOverride(valProp);
        Class<?> valType = valProp.getPropertyType();

        // We should put the new object into the working map in case it
        // is referenced later nested down in the conversion process.
        data.getContext().addConverted(data, paramType, map);
        InboundContext incx = data.getContext();

        // Loop through the property declarations
        StringTokenizer st = new StringTokenizer(value, ",");
        int size = st.countTokens();
        for (int i = 0; i < size; i++) {
            String token = st.nextToken();
            if (token.trim().length() == 0) {
                continue;
            }

            int colonpos = token.indexOf(ProtocolConstants.INBOUND_MAP_ENTRY);
            if (colonpos == -1) {
                throw new ConversionException(paramType, "Missing " + ProtocolConstants.INBOUND_MAP_ENTRY
                        + " in object description: {1}" + token);
            }

            // Convert the value part of the token by splitting it into the
            // type and value (as passed in by Javascript)
            String valStr = token.substring(colonpos + 1).trim();
            String[] splitIv = ConvertUtil.splitInbound(valStr);
            String splitIvValue = splitIv[ConvertUtil.INBOUND_INDEX_VALUE];
            String splitIvType = splitIv[ConvertUtil.INBOUND_INDEX_TYPE];
            InboundVariable valIv = new InboundVariable(incx, null, splitIvType, splitIvValue);
            valIv.dereference();

            /////// added start ///////
            Class orgValType = valType;

            try {
                Map<String, String> tokens = extractInboundTokens(valIv.getValue());

                String refName = tokens.get("__className");

                if (refName != null) {
                    refName = refName.split(":")[1];

                    String className = data.getContext().getInboundVariable(refName).getFormField().getString();

                    try {
                        valType = Thread.currentThread().getContextClassLoader().loadClass(className);
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            /////// added end ///////

            Object val = converterManager.convertInbound(valType, valIv, valProp);

            ////// added start////
            valType = orgValType;
            ////// added end /////

            // Keys (unlike values) do not have type info passed with them
            // Could we have recursive key? - I don't think so because keys
            // must be strings in Javascript
            String keyStr = token.substring(0, colonpos).trim();
            //String[] keySplit = LocalUtil.splitInbound(keyStr);
            //InboundVariable keyIv = new InboundVariable(incx, splitIv[LocalUtil.INBOUND_INDEX_TYPE], splitIv[LocalUtil.INBOUND_INDEX_VALUE]);
            InboundVariable keyIv = new InboundVariable(incx, null, ProtocolConstants.TYPE_STRING, keyStr);
            keyIv.dereference();

            Object key = converterManager.convertInbound(keyType, keyIv, keyProp);

            map.put(key, val);
        }

        return map;
    } catch (ConversionException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ConversionException(paramType, ex);
    }
}

From source file:org.integratedmodelling.thinklab.plugin.ThinklabPlugin.java

protected void loadAnnotatedClass(String subpackage, Class<?> objectClass, Class<?> annotationClass,
        AnnotatedClassHandler handler) throws ThinklabException {

    String ipack = this.getClass().getPackage().getName() + "." + subpackage;

    for (Class<?> cls : MiscUtilities.findSubclasses(objectClass, ipack, getClassLoader())) {

        /*/*from w  ww .jav a  2  s.co  m*/
         * lookup annotation, ensure we can use the class
         */
        if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()))
            continue;

        /*
         * find class with annotation and send back to plugin to process it
         */
        for (Annotation annotation : cls.getAnnotations()) {
            if (annotation.annotationType().equals(annotationClass)) {
                handler.process(annotation, cls, this);
            }
        }
    }
}

From source file:org.integratedmodelling.thinklab.plugin.ThinklabPlugin.java

protected void loadRESTHandlers() throws ThinklabException {

    String ipack = this.getClass().getPackage().getName() + ".rest";

    for (Class<?> cls : MiscUtilities.findSubclasses(IRESTHandler.class, ipack, getClassLoader())) {

        /*/*from   www.j av  a  2s  . c o  m*/
         * lookup annotation, ensure we can use the class
         */
        if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()))
            continue;

        for (Annotation annotation : cls.getAnnotations()) {
            if (annotation instanceof RESTResourceHandler) {

                String path = ((RESTResourceHandler) annotation).path();
                String description = ((RESTResourceHandler) annotation).description();
                RESTManager.get().registerService(path, (Class<?>) cls);

                break;
            }
        }
    }

}