Example usage for java.lang.reflect Modifier isAbstract

List of usage examples for java.lang.reflect Modifier isAbstract

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isAbstract.

Prototype

public static boolean isAbstract(int mod) 

Source Link

Document

Return true if the integer argument includes the abstract modifier, false otherwise.

Usage

From source file:org.mobicents.slee.container.deployment.profile.jpa.ConcreteProfileGenerator.java

private void generateManagementHandlerDelegationMethods(CtClass profileConcreteClass,
        Map<String, CtMethod> methods, Map<String, CtMethod> cmpInterfaceMethods) {
    // boolean useInterceptor = true;
    Class<?> abstractClass = this.profileComponent.getProfileAbstractClass();

    Iterator<Map.Entry<String, CtMethod>> mm = methods.entrySet().iterator();

    Set<String> implementedMethods = new HashSet<String>();
    implementedMethods.addAll(cmpInterfaceMethods.keySet());

    while (mm.hasNext()) {
        String interceptor = ClassGeneratorUtils.MANAGEMENT_HANDLER;

        Map.Entry<String, CtMethod> entry = mm.next();

        CtMethod method = entry.getValue();

        // We should use key, but ClassUtils has different behaviors... go
        // safe!/*  ww  w .  j av  a 2 s.  c o m*/
        String methodKey = method.getName() + method.getSignature();

        if (!implementedMethods.add(methodKey)) {
            // This was already implemented
            continue;
        }

        if (abstractClass != null) {
            try {
                int i = 0;
                Class<?>[] pTypes = new Class[method.getParameterTypes().length];

                for (CtClass pType : method.getParameterTypes()) {
                    if (pType.isPrimitive())
                        pTypes[i++] = ((Class<?>) Class.forName(((CtPrimitiveType) pType).getWrapperName())
                                .getField("TYPE").get(null));
                    else if (pType.isArray())
                        pTypes[i++] = org.apache.commons.lang.ClassUtils.getClass(pType.getName());
                    else
                        pTypes[i++] = Class.forName(pType.getClassFile().getName());
                }

                Method m = abstractClass.getMethod(method.getName(), pTypes);
                interceptor = Modifier.isAbstract(m.getModifiers()) ? interceptor : "super";
            } catch (Exception e) {
                if (!(e instanceof NoSuchMethodException))
                    throw new SLEEException("Problem with Business method generation: " + method.getName(), e);

                // else ignore... we are using default interceptor.
            }
        }

        try {
            ClassGeneratorUtils.generateDelegateMethod(profileConcreteClass, method, interceptor, true);
        } catch (Exception e) {
            throw new SLEEException(e.getMessage(), e);
        }
    }
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

private void validateSetter(ModelSchemaExtractionContext<?> extractionContext, ModelType<?> propertyType,
        Method setter) {//ww w . j  av a  2s  . co m
    if (!Modifier.isAbstract(setter.getModifiers())) {
        throw invalidMethod(extractionContext, "non-abstract setters are not allowed", setter);
    }

    if (!setter.getReturnType().equals(void.class)) {
        throw invalidMethod(extractionContext, "setter method must have void return type", setter);
    }

    Type[] setterParameterTypes = setter.getGenericParameterTypes();
    if (setterParameterTypes.length != 1) {
        throw invalidMethod(extractionContext, "setter method must have exactly one parameter", setter);
    }

    ModelType<?> setterType = ModelType.paramType(setter, 0);
    if (!setterType.equals(propertyType)) {
        String message = "setter method param must be of exactly the same type as the getter returns (expected: "
                + propertyType + ", found: " + setterType + ")";
        throw invalidMethod(extractionContext, message, setter);
    }
}

From source file:com.github.helenusdriver.driver.impl.RootClassInfoImpl.java

/**
 * Instantiates a new <code>RootClassInfoImpl</code> object.
 *
 * @author paouelle//from   w w  w.  j a v a2  s  .c  om
 *
 * @param  mgr the non-<code>null</code> statement manager
 * @param  clazz the root class of POJO for which to get a class info object for
 * @param  types the non-<code>null</code> map of all type class infos
 * @throws NullPointerException if <code>clazz</code> is <code>null</code>
 * @throws IllegalArgumentException if <code>clazz</code> or any of its type
 *         classes don't represent valid POJO classes
 */
private RootClassInfoImpl(StatementManagerImpl mgr, Class<T> clazz,
        Map<Class<? extends T>, TypeClassInfoImpl<? extends T>> types) {
    super(mgr, clazz, RootEntity.class);
    // first make sure the class is abstract
    org.apache.commons.lang3.Validate.isTrue(Modifier.isAbstract(clazz.getModifiers()),
            "root entity class '%s', must be abstract", clazz.getSimpleName());
    this.ctypes = types;
    this.ntypes = types.values().stream()
            .collect(Collectors.toMap(tcinfo -> tcinfo.getType(), tcinfo -> tcinfo));
    validateAndComplementSchema();
}

From source file:org.structr.core.module.ModuleService.java

public Class getRelationshipClass(final String name) {

    Class ret = AbstractNode.class;

    if ((name != null) && (name.length() > 0)) {

        ret = relationshipClassCache.get(name);

        if (ret == null) {

            for (String possiblePath : relationshipPackages) {

                if (possiblePath != null) {

                    try {

                        Class nodeClass = Class.forName(possiblePath + "." + name);

                        if (!Modifier.isAbstract(nodeClass.getModifiers())) {

                            relationshipClassCache.put(name, nodeClass);

                            // first match wins
                            break;

                        }/*  w  ww  .java 2s  .  co  m*/

                    } catch (ClassNotFoundException ex) {

                        // ignore
                    }

                }

            }

        }

    }

    return (ret);

}

From source file:ca.uhn.fhir.context.FhirContext.java

/**
 * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
 * for extending the core library./*from w ww .  j av  a  2s.c om*/
 */
public RuntimeResourceDefinition getResourceDefinition(Class<? extends IBaseResource> theResourceType) {
    validateInitialized();
    if (theResourceType == null) {
        throw new NullPointerException("theResourceType can not be null");
    }
    if (Modifier.isAbstract(theResourceType.getModifiers())) {
        throw new IllegalArgumentException(
                "Can not scan abstract or interface class (resource definitions must be concrete classes): "
                        + theResourceType.getName());
    }

    RuntimeResourceDefinition retVal = (RuntimeResourceDefinition) myClassToElementDefinition
            .get(theResourceType);
    if (retVal == null) {
        retVal = scanResourceType(theResourceType);
    }
    return retVal;
}

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

/**
 * Return XML schema for the specified type, suitable for insertion into
 * the &lt;types&gt; element of a WSDL document, or underneath an
 * &lt;element&gt; or &lt;attribute&gt; declaration.
 *
 * @param javaType the Java Class we're writing out schema for
 * @param types the Java2WSDL Types object which holds the context
 *              for the WSDL being generated.
 * @return a type element containing a schema simpleType/complexType
 * @see org.apache.axis.wsdl.fromJava.Types
 */// w w w . ja  va2  s  .  c  o  m
public Element writeSchema(Class javaType, Types types) throws Exception {

    // ComplexType representation of bean class
    Element complexType = types.createElement("complexType");

    // See if there is a super class, stop if we hit a stop class
    Element e = null;
    Class superClass = javaType.getSuperclass();
    BeanPropertyDescriptor[] superPd = null;
    List stopClasses = types.getStopClasses();
    if (superClass != null && superClass != java.lang.Object.class && superClass != java.lang.Exception.class
            && superClass != java.lang.Throwable.class && superClass != java.lang.RuntimeException.class
            && superClass != java.rmi.RemoteException.class && superClass != org.apache.axis.AxisFault.class
            && (stopClasses == null || !(stopClasses.contains(superClass.getName())))) {
        // Write out the super class
        String base = types.writeType(superClass);
        Element complexContent = types.createElement("complexContent");
        complexType.appendChild(complexContent);
        Element extension = types.createElement("extension");
        complexContent.appendChild(extension);
        extension.setAttribute("base", base);
        e = extension;
        // Get the property descriptors for the super class
        TypeDesc superTypeDesc = TypeDesc.getTypeDescForClass(superClass);
        if (superTypeDesc != null) {
            superPd = superTypeDesc.getPropertyDescriptors();
        } else {
            superPd = BeanUtils.getPd(superClass, null);
        }
    } else {
        e = complexType;
    }

    // Add fields under sequence element.
    // Note: In most situations it would be okay
    // to put the fields under an all element.
    // However it is illegal schema to put an
    // element with minOccurs=0 or maxOccurs>1 underneath
    // an all element.  This is the reason why a sequence
    // element is used.
    Element all = types.createElement("sequence");
    e.appendChild(all);

    if (Modifier.isAbstract(javaType.getModifiers())) {
        complexType.setAttribute("abstract", "true");
    }

    // Serialize each property
    for (int i = 0; i < propertyDescriptor.length; i++) {
        String propName = propertyDescriptor[i].getName();

        // Don't serializer properties named class
        boolean writeProperty = true;
        if (propName.equals("class")) {
            writeProperty = false;
        }

        // Don't serialize the property if it is present
        // in the super class property list
        if (superPd != null && writeProperty) {
            for (int j = 0; j < superPd.length && writeProperty; j++) {
                if (propName.equals(superPd[j].getName())) {
                    writeProperty = false;
                }
            }
        }
        if (!writeProperty) {
            continue;
        }

        // If we have type metadata, check to see what we're doing
        // with this field.  If it's an attribute, skip it.  If it's
        // an element, use whatever qname is in there.  If we can't
        // find any of this info, use the default.

        if (typeDesc != null) {
            Class fieldType = propertyDescriptor[i].getType();
            FieldDesc field = typeDesc.getFieldByName(propName);

            if (field != null) {
                QName qname = field.getXmlName();
                QName fieldXmlType = field.getXmlType();
                boolean isAnonymous = fieldXmlType != null && fieldXmlType.getLocalPart().startsWith(">");

                if (qname != null) {
                    // FIXME!
                    // Check to see if this is in the right namespace -
                    // if it's not, we need to use an <element ref="">
                    // to represent it!!!

                    // Use the default...
                    propName = qname.getLocalPart();
                }
                if (!field.isElement()) {
                    writeAttribute(types, propName, fieldType, fieldXmlType, complexType);
                } else {
                    writeField(types, propName, fieldXmlType, fieldType, propertyDescriptor[i].isIndexed(),
                            field.isMinOccursZero(), all, isAnonymous, ((ElementDesc) field).getItemQName());
                }
            } else {
                writeField(types, propName, null, fieldType, propertyDescriptor[i].isIndexed(), false, all,
                        false, null);
            }
        } else {
            boolean done = false;
            if (propertyDescriptor[i] instanceof FieldPropertyDescriptor) {
                FieldPropertyDescriptor fpd = (FieldPropertyDescriptor) propertyDescriptor[i];
                Class clazz = fpd.getField().getType();
                if (types.getTypeQName(clazz) != null) {
                    writeField(types, propName, null, clazz, false, false, all, false, null);

                    done = true;
                }
            }
            if (!done) {
                writeField(types, propName, null, propertyDescriptor[i].getType(),
                        propertyDescriptor[i].isIndexed(), false, all, false, null);
            }

        }
    }

    // done
    return complexType;
}

From source file:ome.services.graphs.GraphPathBean.java

/**
 * Process the Hibernate domain object model to initialize this class' instance fields.
 * No other method should write to them.
 * @param sessionFactory the Hibernate session factory
 *//*from w  w w .  ja  v  a2  s  . co  m*/
private void initialize(SessionFactoryImplementor sessionFactory) {
    /* note all the direct superclasses */
    final Map<String, String> superclasses = new HashMap<String, String>();
    final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
    for (final String className : classesMetadata.keySet()) {
        try {
            final Class<?> actualClass = Class.forName(className);
            if (IObject.class.isAssignableFrom(actualClass)) {
                classesBySimpleName.put(actualClass.getSimpleName(), actualClass.asSubclass(IObject.class));
                final Set<String> subclassNames = sessionFactory.getEntityPersister(className)
                        .getEntityMetamodel().getSubclassEntityNames();
                for (final String subclassName : subclassNames) {
                    if (!subclassName.equals(className)) {
                        final Class<?> actualSubclass = Class.forName(subclassName);
                        if (actualSubclass.getSuperclass() == actualClass) {
                            superclasses.put(subclassName, className);
                        }
                    }
                }
            } else {
                log.warn("mapped class " + className + " is not a " + IObject.class.getName());
            }
        } catch (ClassNotFoundException e) {
            log.error("could not instantiate class", e);
        }
    }
    /* note the indirect superclasses and subclasses */
    for (final Entry<String, String> superclassRelationship : superclasses.entrySet()) {
        final String startClass = superclassRelationship.getKey();
        String superclass = superclassRelationship.getValue();
        while (superclass != null) {
            allSuperclasses.put(startClass, superclass);
            allSubclasses.put(superclass, startClass);
            superclass = superclasses.get(superclass);
        }
    }
    /* queue for processing all the properties of all the mapped entities: name, type, nullability */
    final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>();
    final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>();
    for (final Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) {
        final String className = classMetadata.getKey();
        final ClassMetadata metadata = classMetadata.getValue();
        /* note name of identifier property */
        classIdProperties.put(metadata.getEntityName(), metadata.getIdentifierPropertyName());
        /* queue other properties */
        final String[] propertyNames = metadata.getPropertyNames();
        final Type[] propertyTypes = metadata.getPropertyTypes();
        final boolean[] propertyNullabilities = metadata.getPropertyNullability();
        for (int i = 0; i < propertyNames.length; i++) {
            final List<String> propertyPath = Collections.singletonList(propertyNames[i]);
            propertyQueue.add(
                    new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i]));
        }
        final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length);
        propertyNamesSet.addAll(Arrays.asList(propertyNames));
        allPropertyNames.put(className, propertyNamesSet);
    }
    /* process each property to note entity linkages */
    while (!propertyQueue.isEmpty()) {
        final PropertyDetails property = propertyQueue.remove();
        if (ignoreProperty(property.path.get(property.path.size() - 1))) {
            continue;
        }
        /* if the property has a component type, queue the parts for processing */
        if (property.type instanceof ComponentType) {
            final ComponentType componentType = (ComponentType) property.type;
            final String[] componentPropertyNames = componentType.getPropertyNames();
            final Type[] componentPropertyTypes = componentType.getSubtypes();
            final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability();
            for (int i = 0; i < componentPropertyNames.length; i++) {
                final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1);
                componentPropertyPath.addAll(property.path);
                componentPropertyPath.add(componentPropertyNames[i]);
                propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath,
                        componentPropertyTypes[i], componentPropertyNullabilities[i]));
            }
        } else {
            /* determine if another mapped entity class is linked by this property */
            final boolean isAssociatedEntity;
            if (property.type instanceof CollectionType) {
                final CollectionType ct = (CollectionType) property.type;
                isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType()
                        .isEntityType();
            } else {
                isAssociatedEntity = property.type instanceof AssociationType;
            }
            /* the property can link to entities, so process it further */
            String propertyPath = Joiner.on('.').join(property.path);
            /* find if the property is accessible (e.g., not protected) */
            boolean propertyIsAccessible = false;
            String classToInstantiateName = property.holder;
            Class<?> classToInstantiate = null;
            try {
                classToInstantiate = Class.forName(classToInstantiateName);
                while (Modifier.isAbstract(classToInstantiate.getModifiers())) {
                    classToInstantiateName = allSubclasses.get(classToInstantiateName).iterator().next();
                    classToInstantiate = Class.forName(classToInstantiateName);
                }
                try {
                    PropertyUtils.getNestedProperty(classToInstantiate.newInstance(), propertyPath);
                    propertyIsAccessible = true;
                } catch (NoSuchMethodException e) {
                    /* expected for collection properties */
                } catch (NestedNullException e) {
                    log.warn("guessing " + propertyPath + " of " + property.holder + " to be accessible");
                    propertyIsAccessible = true;
                }
            } catch (ReflectiveOperationException e) {
                log.error("could not probe property " + propertyPath + " of " + property.holder, e);
                continue;
            }
            /* build property report line for log */
            final char arrowShaft = property.isNullable ? '-' : '=';
            final StringBuffer sb = new StringBuffer();
            sb.append(property.holder);
            sb.append(' ');
            for (final String propertyName : property.path) {
                sb.append(arrowShaft);
                sb.append(arrowShaft);
                sb.append(propertyName);
            }
            sb.append(arrowShaft);
            sb.append(arrowShaft);
            sb.append("> ");
            final String valueClassName;
            if (isAssociatedEntity) {
                valueClassName = ((AssociationType) property.type).getAssociatedEntityName(sessionFactory);
                sb.append(valueClassName);
            } else {
                valueClassName = null;
                sb.append("value");
            }
            if (property.type.isCollectionType()) {
                sb.append("[]");
            }
            if (!propertyIsAccessible) {
                sb.append(" (inaccessible)");
            }
            /* determine from which class the property is inherited, if at all */
            String superclassWithProperty = null;
            String currentClass = property.holder;
            while (true) {
                currentClass = superclasses.get(currentClass);
                if (currentClass == null) {
                    break;
                } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) {
                    superclassWithProperty = currentClass;
                }
            }
            /* check if the property actually comes from an interface */
            final String declaringClassName = superclassWithProperty == null ? property.holder
                    : superclassWithProperty;
            final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName,
                    property.path.get(0));
            /* report where the property is declared */
            if (superclassWithProperty != null) {
                sb.append(" from ");
                sb.append(superclassWithProperty);
            } else {
                if (interfaceForProperty != null) {
                    sb.append(" see ");
                    sb.append(interfaceForProperty.getName());
                    /* It would be nice to set PropertyDetails to have the interface as the holder,
                     * but then properties would not be unique by declarer class and instance ID. */
                }
                /* entity linkages by non-inherited properties are recorded */
                if (valueClassName == null && property.path.size() > 1) {
                    /* assume that the top-level property suffices for describing simple properties */
                    log.debug("recording " + propertyPath + " as " + property.path.get(0));
                    propertyPath = property.path.get(0);
                }
                final Entry<String, String> classPropertyName = Maps.immutableEntry(property.holder,
                        propertyPath);
                if (valueClassName == null) {
                    simpleProperties.put(property.holder, propertyPath);
                } else {
                    linkedTo.put(property.holder, Maps.immutableEntry(valueClassName, propertyPath));
                    linkedBy.put(valueClassName, classPropertyName);
                }
                final PropertyKind propertyKind;
                if (property.type.isCollectionType()) {
                    propertyKind = PropertyKind.COLLECTION;
                } else if (property.isNullable) {
                    propertyKind = PropertyKind.OPTIONAL;
                } else {
                    propertyKind = PropertyKind.REQUIRED;
                }
                propertyKinds.put(classPropertyName, propertyKind);
                if (propertyIsAccessible) {
                    accessibleProperties.add(classPropertyName);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(sb.toString());
            }
        }
    }
    log.info("initialized graph path bean with " + propertyKinds.size() + " properties");
}

From source file:org.ajax4jsf.builder.config.ComponentBaseBean.java

public boolean isSuperSetTransientMethodExists() {
    try {//from  w w  w . j a  v a2s.  com
        Class superClass = getLoader().loadClass(getSuperclass());
        Class[] signature = { boolean.class };
        try {
            Method m = superClass.getMethod("setTransient", signature);
            return !Modifier.isAbstract(m.getModifiers());
        } catch (NoSuchMethodException e) {
            return false;
        }
    } catch (ClassNotFoundException e) {
        getLog().error("superclass not found for tag " + getTag().getName(), e);
        return false;
    }
}

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)
    }/*from w  w w.jav  a 2  s  .c o m*/
    Class<? extends T> subclass = inspector.findMatchingSubclass(beanClass, fields);
    return instantiate(subclass);
}

From source file:org.apache.brooklyn.core.catalog.internal.CatalogClasspathDo.java

/** removes inner classes (non-static nesteds) and others; 
 * bear in mind named ones will be hard to instantiate without the outer class instance) */
private <T> Iterable<Class<? extends T>> excludeInvalidClasses(Iterable<Class<? extends T>> input) {
    Predicate<Class<? extends T>> f = new Predicate<Class<? extends T>>() {
        @Override/*from   w  w w . j  a  v  a2  s  . co m*/
        public boolean apply(@Nullable Class<? extends T> input) {
            if (input == null)
                return false;
            if (input.isLocalClass() || input.isAnonymousClass())
                return false;
            if (Modifier.isAbstract(input.getModifiers())) {
                if (input.getAnnotation(ImplementedBy.class) == null)
                    return false;
            }
            // non-abstract top-level classes are okay
            if (!input.isMemberClass())
                return true;
            if (!Modifier.isStatic(input.getModifiers()))
                return false;
            // nested classes only okay if static
            return true;
        }
    };
    return Iterables.filter(input, f);
}