Tool for Class objects filtering

nikelin 0 Tallied Votes 480 Views Share

Helps to filter objects by interfaces and annotations their contains/implements with respect to parental relations.

package com.vio.utils;

import java.lang.annotation.Annotation;

/**
* Interfaces/Annotations filter
*/
public class InterfacesFilter {
    private Class<?>[] interfaces;
    private Class<? extends Annotation>[] annotations;

    public InterfacesFilter( Class<?>[] interfaces ) {
        this( interfaces, new Class[] {} );
    }

    public InterfacesFilter( Class<?>[] interfaces, Class<? extends Annotation>[] annotations ) {
        this.interfaces = interfaces;
        this.annotations = annotations;
    }

    public boolean filter( Class<?> filterable ) {
        return this.filter( filterable, true );
    }

    public boolean filter( Class<?> filterable, boolean allowNesting ) {
        for ( Class<? extends Annotation> annon : this.annotations ) {
            Class<?> parent = filterable;
            boolean found;
            do {
                found = parent.getAnnotation( annon ) != null;
            } while( allowNesting && !found && null != ( parent = parent.getSuperclass() ) );

            if ( !found ) {
                return false;
            }
        }

        for ( Class<?> interfaceClass : this.interfaces ) {
            Class<?> parent = filterable;
            boolean found;
            do {
                found = interfaceClass.isAssignableFrom(parent);
            } while( allowNesting && !found && null != ( parent = parent.getSuperclass() ) );

            if ( !found ) {
                return false;
            }
        }

        return true;
    }

}