View Javadoc

    1   package net.sourceforge.pmd.lang.java.typeresolution;
    2
    3   import java.util.Arrays;
    4   import java.util.List;
    5
    6   import net.sourceforge.pmd.lang.ast.Node;
    7   import net.sourceforge.pmd.lang.java.ast.TypeNode;
    8   import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
    9
    10  public class TypeHelper {
    11
    12  	public static boolean isA(TypeNode n, Class<?> clazz) {
    13  		return subclasses(n, clazz);
    14  	}
    15
    16  	public static boolean isEither(TypeNode n, Class<?> class1, Class<?> class2) {
    17  		return subclasses(n, class1) || subclasses(n, class2);
    18  	}
    19
    20  	public static boolean isA(VariableNameDeclaration vnd, Class<?> clazz) {
    21  		Class<?> type = vnd.getType();
    22  		return type != null && type.equals(clazz) || type == null
    23  		&& (clazz.getSimpleName().equals(vnd.getTypeImage()) || clazz.getName().equals(vnd.getTypeImage()));
    24  	}
    25
    26  	public static boolean isEither(VariableNameDeclaration vnd, Class<?> class1, Class<?> class2) {
    27  		return isA(vnd, class1) || isA(vnd, class2);
    28  	}
    29
    30  	public static boolean isNeither(VariableNameDeclaration vnd, Class<?> class1, Class<?> class2) {
    31  		return !isA(vnd, class1) &&  !isA(vnd, class2);
    32  	}
    33
    34  	public static boolean subclasses(TypeNode n, Class<?> clazz) {
    35  		Class type = n.getType();
    36  		if (type == null) {
    37  			return clazz.getSimpleName().equals(((Node) n).getImage()) || clazz.getName().equals(((Node) n).getImage());
    38  		}
    39
    40  		if (type.equals(clazz)) {
    41  			return true;
    42  		}
    43
    44  		List<Class> implementors = Arrays.asList(type.getInterfaces());
    45  		if (implementors.contains(clazz)) {
    46  			return true;
    47  		}
    48  		Class<?> superC = type.getSuperclass();
    49  		while (superC != null && !superC.equals(Object.class)) {
    50  			if (superC.equals(clazz)) {
    51  				return true;
    52  			}
    53  			superC = superC.getSuperclass();
    54  		}
    55  		return false;
    56  	}
    57  }