Skip to content

Commit

Permalink
fix: Improve robustness and logging of parent interface and superclas…
Browse files Browse the repository at this point in the history
…s access
  • Loading branch information
kgilpin committed Jul 29, 2021
1 parent 637f904 commit a24f056
Showing 1 changed file with 29 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,20 @@ class CtClassUtil {
/**
* Checks whether or not two types are equal or related via class hierarchy or interface
* implementation.
*
* @param candidateChildClass The child class
* @param parentClassName The name of the parent class
* @param parentClassName The name of the parent class
* @return {@code true} if the parent class is a super class of the child or equal to the child.
* Otherwise, {@code false}.
* Otherwise, {@code false}.
*/
public static Boolean isChildOf(CtClass candidateChildClass, String parentClassName) {
try {
if (candidateChildClass.getName().equals(parentClassName)) {
return true;
}
if (candidateChildClass.getName().equals(parentClassName)) {
return true;
}

for (CtClass superType : candidateChildClass.getInterfaces()) {
CtClass[] interfaces = tryClass(candidateChildClass, "interfaces", candidateChildClass::getInterfaces);
if ( interfaces != null ) {
for (CtClass superType : interfaces) {
if (superType.getName().equals(parentClassName)) {
return true;
} else {
Expand All @@ -32,21 +34,32 @@ public static Boolean isChildOf(CtClass candidateChildClass, String parentClassN
}
}
}
}

CtClass superClass = candidateChildClass.getSuperclass();
while (superClass != null) {
if (superClass.getName().equals(parentClassName)) {
return true;
}
superClass = superClass.getSuperclass();
CtClass superClass = tryClass(candidateChildClass, "superclass", candidateChildClass::getSuperclass);
while (superClass != null) {
if (superClass.getName().equals(parentClassName)) {
return true;
}
final CtClass cls = superClass;
superClass = tryClass(cls, "superclass", cls::getSuperclass);
}

return false;
}

private static <V> V tryClass(CtClass cls, String member, ClassAccessor<V> accessor) {
try {
return accessor.navigate();
} catch (NotFoundException e) {
if (Properties.DebugHooks) {
Logger.println("could not resolve class hierarchy");
Logger.println(e);
Logger.printf("NotFoundException resolving %s of class %s: %s\n", member, cls.getName(), e.getMessage());
}
return null;
}
}

return false;
interface ClassAccessor<V> {
V navigate() throws NotFoundException;
}
}

0 comments on commit a24f056

Please sign in to comment.