mirror of
https://github.com/github/codeql.git
synced 2025-12-16 16:53:25 +01:00
Java: note that classes with entirely private constructors can't be subclassed
This commit is contained in:
@@ -15,6 +15,10 @@
|
||||
|
||||
import java
|
||||
|
||||
private predicate hasASubclass(RefType t) {
|
||||
exists(RefType sub | sub != t | sub.getAnAncestor() = t)
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds if this type is either `final` or
|
||||
* `private` and without subtypes.
|
||||
@@ -24,7 +28,11 @@ private predicate cannotBeExtended(RefType t) {
|
||||
or
|
||||
// If the class is private, all possible subclasses are known.
|
||||
t.isPrivate() and
|
||||
not exists(RefType sub | sub != t | sub.getAnAncestor() = t)
|
||||
not hasASubclass(t)
|
||||
or
|
||||
// If the class only has private constructors, all possible subclasses are known.
|
||||
forex(Constructor c | c.getDeclaringType() = t | c.isPrivate()) and
|
||||
not hasASubclass(t)
|
||||
}
|
||||
|
||||
from MethodCall m, Constructor c, Class clazz
|
||||
|
||||
@@ -30,4 +30,18 @@ public class Test {
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static class AllPrivateConstructors {
|
||||
Thread myThread;
|
||||
|
||||
private AllPrivateConstructors() {
|
||||
myThread = new Thread("myThread");
|
||||
// OK - class cannot be extended outside this file, and is not in fact extended
|
||||
myThread.start();
|
||||
}
|
||||
|
||||
public static AllPrivateConstructors create() {
|
||||
return new AllPrivateConstructors();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user