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 final class TypeHelper {
14  
15      private TypeHelper() {
16          // utility class
17      }
18  
19  	public static boolean isA(TypeNode n, Class<?> clazz) {
20  		return subclasses(n, clazz);
21  	}
22  
23  	public static boolean isEither(TypeNode n, Class<?> class1, Class<?> class2) {
24  		return subclasses(n, class1) || subclasses(n, class2);
25  	}
26  	
27  	public static boolean isA(TypedNameDeclaration vnd, Class<?> clazz) {
28  		Class<?> type = vnd.getType();
29  		return type != null && type.equals(clazz) || type == null
30  		&& (clazz.getSimpleName().equals(vnd.getTypeImage()) || clazz.getName().equals(vnd.getTypeImage()));
31  	}
32  
33  	public static boolean isEither(TypedNameDeclaration vnd, Class<?> class1, Class<?> class2) {
34  		return isA(vnd, class1) || isA(vnd, class2);
35  	}
36  	
37  	public static boolean isNeither(TypedNameDeclaration vnd, Class<?> class1, Class<?> class2) {
38  		return !isA(vnd, class1) &&  !isA(vnd, class2);
39  	}
40  	
41  	public static boolean subclasses(TypeNode n, Class<?> clazz) {
42  		Class<?> type = n.getType();
43  		if (type == null) {
44  			return clazz.getSimpleName().equals(((Node) n).getImage()) || clazz.getName().equals(((Node) n).getImage());
45  		}
46  
47  		if (type.equals(clazz)) {
48  			return true;
49  		}
50  
51  		List<Class<?>> implementors = Arrays.asList(type.getInterfaces());
52  		if (implementors.contains(clazz)) {
53  			return true;
54  		}
55  		Class<?> superC = type.getSuperclass();
56  		while (superC != null && !superC.equals(Object.class)) {
57  			if (superC.equals(clazz)) {
58  				return true;
59  			}
60  			superC = superC.getSuperclass();
61  		}
62  		return false;
63  	}
64  }