Example usage for com.google.common.base Predicates assignableFrom

List of usage examples for com.google.common.base Predicates assignableFrom

Introduction

In this page you can find the example usage for com.google.common.base Predicates assignableFrom.

Prototype

@GwtIncompatible("Class.isAssignableFrom")
@Beta
public static Predicate<Class<?>> assignableFrom(Class<?> clazz) 

Source Link

Document

Returns a predicate that evaluates to true if the class being tested is assignable from the given class.

Usage

From source file:net.tridentsdk.server.entity.EntityManager.java

/**
 * Gets all entities with the given type class
 *
 * @param type the type to search for entities
 * @param <T>  the entity type//ww  w.j av a 2  s  .c  om
 * @return the list of entities with the specified type
 */
public <T> ArrayList<T> getEntities(final Class<T> type) {
    Predicate<Entity> pred = new Predicate<Entity>() {
        @Override
        public boolean apply(Entity e) {
            return Predicates.assignableFrom(type.getClass()).apply(e.getClass());
        }
    };

    return (ArrayList<T>) Lists.newArrayList(Iterators.filter(this.entities.values().iterator(), pred));
}

From source file:org.apache.abdera2.common.misc.MorePredicates.java

public static <T> Selector<T> assignableFrom(Class<T> _class, String method, Class<?> _test) {
    return PropertySelector.<T>create(_class, method, Predicates.assignableFrom(_test));
}

From source file:org.obm.healthcheck.handlers.RootHandler.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from   w w w  .  j  a  va  2  s.c o  m*/
public Set<EndpointDescription> root() {
    Set<EndpointDescription> endpoints = Sets.newHashSet();
    Iterable<Class<?>> classes = Iterables.filter(application.getClasses(),
            Predicates.assignableFrom(HealthCheckHandler.class));

    for (Class<?> handlerClass : classes) {
        AbstractResource resource = IntrospectionModeller.createResource(handlerClass);
        String resourcePath = resource.getPath().getValue();

        for (AbstractSubResourceMethod endpoint : resource.getSubResourceMethods()) {
            endpoints.add(new EndpointDescription(endpoint.getHttpMethod(),
                    resourcePath + '/' + endpoint.getPath().getValue()));
        }
    }

    return endpoints;
}

From source file:net.tridentsdk.server.entity.EntityHandler.java

/**
 * Gets all entities with the given type class
 *
 * @param type the type to search for entities
 * @param <T>  the entity type//from  w ww  .j ava2s.co m
 * @return the list of entities with the specified type
 */
public <T extends Entity> List<T> entities(final Class<T> type) {
    Predicate<T> pred = new Predicate<T>() {
        @Override
        public boolean apply(Entity e) {
            return Predicates.assignableFrom(type.getClass()).apply(e.getClass());
        }
    };

    return Lists.newArrayList(Iterators.filter((Iterator<T>) this.entities.values().iterator(), pred));
}

From source file:org.terasology.entitySystem.pojo.PojoEventSystem.java

@Override
public void registerEvent(String name, Class<? extends Event> eventType) {
    if (name != null && !name.isEmpty()) {
        eventIdMap.put(name, eventType);
    }//from   w ww  .  j  a  v a 2s .  c o m
    logger.debug("Registering event {}", eventType.getSimpleName());
    for (Class parent : Reflections.getAllSuperTypes(eventType, Predicates.assignableFrom(Event.class))) {
        if (!AbstractEvent.class.equals(parent) && !Event.class.equals(parent)) {
            childEvents.put(parent, eventType);
        }
    }
}

From source file:com.tacitknowledge.flip.spi.ServiceProvider.java

/**
 * Finds classes by the annotation and which extends from the resultingClass 
 * and instantiates them. If the classes which are marked by the annotation 
 * and do not extend the resultingClass then they are ignored. 
 * //w  ww. j a  v  a2  s.c o m
 * @param <T> the class of objects to be returned.
 * @param annotatedClass the annotation which marks the classes to find.
 * @param resultingClass the class from which the found classes should extend. 
 * It could be an interface or a class. 
 * @return the collection of objects found.
 */
public <T> Collection<T> find(final Class<? extends Annotation> annotatedClass, final Class<T> resultingClass) {
    final Collection<Class<?>> filteredList = Collections2.filter(findClass(annotatedClass),
            Predicates.assignableFrom(resultingClass));

    return Collections2.transform(filteredList, new ClassToObjectTransformer<T>());
}

From source file:org.terasology.entitySystem.event.internal.EventSystemImpl.java

@Override
public void registerEvent(SimpleUri uri, Class<? extends Event> eventType) {
    eventIdMap.put(uri, eventType);// www .  j ava 2  s.co m
    logger.debug("Registering event {}", eventType.getSimpleName());
    for (Class parent : ReflectionUtils.getAllSuperTypes(eventType, Predicates.assignableFrom(Event.class))) {
        if (!AbstractConsumableEvent.class.equals(parent) && !Event.class.equals(parent)) {
            childEvents.put(parent, eventType);
        }
    }
    if (shouldAddToLibrary(eventType)) {
        eventLibrary.register(uri, eventType);
    }
}

From source file:org.apache.brooklyn.core.typereg.RegisteredTypePredicates.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Predicate<RegisteredType> subtypeOf(final Class<?> filter) {
    // the assignableFrom predicate checks if this class is assignable from the subsequent *input*.
    // in other words, we're checking if any input is a subtype of this class
    return anySuperType((Predicate) Predicates.assignableFrom(filter));
}

From source file:com.kolich.curacao.components.ComponentTable.java

private final Object instantiate(final ImmutableSet<Class<?>> allComponents,
        final Map<Class<?>, Object> componentMap, final Class<?> component, final Set<Class<?>> depStack)
        throws Exception {
    // Locate a single constructor worthy of injecting with ~other~
    // components, if any.  May be null.
    final Constructor<?> ctor = getInjectableConstructor(component);
    Object instance = null;//from   w w w  . j a  v  a  2 s .c  o  m
    if (ctor == null) {
        // Class.newInstance() is evil, so we do the ~right~ thing
        // here to instantiate a new instance of the component
        // using the preferred getConstructor() idiom.
        instance = component.getConstructor().newInstance();
    } else {
        final Class<?>[] types = ctor.getParameterTypes();
        // Construct an array of Object's outright to avoid system array
        // copying from a List/Collection to a vanilla array later.
        final Object[] params = new Object[types.length];
        for (int i = 0, l = types.length; i < l; i++) {
            final Class<?> type = types[i];
            // <https://github.com/markkolich/curacao/issues/7>
            // If the dependency stack contains the type we're tasked with
            // instantiating, but the component map already contains an
            // instance with this type, then it's ~not~ a real circular
            // dependency -- we already have what we need to fulfill the
            // request.
            if (depStack.contains(type) && !componentMap.containsKey(type)) {
                // Circular dependency detected, A -> B, but B -> A.
                // Or, A -> B -> C, but C -> A.  Can't do that, sorry!
                throw new CuracaoException("CIRCULAR DEPENDENCY DETECTED! " + "While trying to instantiate @"
                        + COMPONENT_ANNOTATION_SN + ": " + component.getCanonicalName() + " it depends "
                        + "on the other components (" + depStack + ")");
            } else if (componentMap.containsKey(type)) {
                // The component mapping table already contained an instance
                // of the component type we're after.  Simply grab it and
                // add it to the constructor parameter list.
                params[i] = componentMap.get(type);
            } else if (type.isInterface()) {
                // Interfaces are handled differently.  The logic here
                // involves finding some component, if any, that implements
                // the discovered interface type.  If one is found, we attempt
                // to instantiate it, if it hasn't been instantiated already.
                final Class<?> found = Iterables.tryFind(allComponents, Predicates.assignableFrom(type))
                        .orNull();
                if (found != null) {
                    // We found some component that implements the discovered
                    // interface.  Let's try to instantiate it.  Add the
                    // ~interface~ class type ot the dependency stack.
                    depStack.add(type);
                    final Object recursiveInstance =
                            // Recursion!
                            instantiate(allComponents, componentMap, found, depStack);
                    // Add the freshly instantiated component instance to the
                    // new component mapping table as we go.
                    componentMap.put(found, recursiveInstance);
                    // Add the freshly instantiated component instance to the
                    // list of component constructor arguments/parameters.
                    params[i] = recursiveInstance;
                } else {
                    // Found no component that implements the given interface.
                    params[i] = null;
                }
            } else {
                // The component mapping table does not contain a
                // component for the given class.  We might need to
                // instantiate a fresh one and then inject, checking
                // carefully for circular dependencies.
                depStack.add(component);
                final Object recursiveInstance =
                        // Recursion!
                        instantiate(allComponents, componentMap, type, depStack);
                // Add the freshly instantiated component instance to the
                // new component mapping table as we go.
                componentMap.put(type, recursiveInstance);
                // Add the freshly instantiated component instance to the
                // list of component constructor arguments/parameters.
                params[i] = recursiveInstance;
            }
        }
        instance = ctor.newInstance(params);
    }
    // The freshly freshly instantiated component instance may implement
    // a set of interfaces, and therefore, can be used to inject other
    // components that have specified it using only the interface and not
    // a concrete implementation.  As such, add each implemented interface
    // to the component map pointing directly to the concrete implementation
    // instance.
    for (final Class<?> interfacz : instance.getClass().getInterfaces()) {
        // If the component is decorated with 'CuracaoComponent' don't
        // bother trying to add said interfaces to the underlying component
        // map (they're special, internal to the toolkit, unrelated to
        // user defined interfaces).
        if (!interfacz.isAssignableFrom(CuracaoComponent.class)) {
            componentMap.put(interfacz, instance);
        }
    }
    return instance;
}

From source file:org.apache.brooklyn.core.typereg.RegisteredTypes.java

/** 
 * Queries recursively the given types (either {@link Class} or {@link RegisteredType}) 
 * to see whether any inherit from the given {@link Class} */
public static boolean isAnyTypeSubtypeOf(Set<Object> candidateTypes, Class<?> superType) {
    return isAnyTypeOrSuperSatisfying(candidateTypes, Predicates.assignableFrom(superType));
}