View Javadoc

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