Java Reference
In-Depth Information
Compliant Solution (Final Classes with Public Methods)
This compliant solution declares the Point class as package-private in accordance with
its status as not part of any public API:
Click here to view code image
final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public void getPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
Atop-levelclass,suchas Point ,cannotbedeclaredprivate.Package-private accessib-
ility is acceptable, provided package insertion attacks are avoided. (See “ ENV01-J. Place
all security-sensitive code in a single JAR and sign and seal it [Long 2012].) A package
insertion attack occurs when, at runtime, any protected or package-private members of a
class can be called directly by a class that is maliciously inserted into the same package.
However,thisattack isdifficult tocarryoutinpractice because, inaddition totherequire-
ment of infiltrating the package, the target and the untrusted class must be loaded by the
same class loader. Untrusted code is typically deprived of such levels of access.
Because the class is final, the getPoint() method can be declared public. A public
subclassthatviolatesthisrulecannotoverridethemethodandexposeittountrustedcode,
soitsaccessibilityisirrelevant.Fornonfinalclasses,reducingtheaccessibilityofmethods
to private or package-private eliminates this threat.
Compliant Solution (Nonfinal Classes with Nonpublic Methods)
This compliant solution declares the Point class and its getPoint() method as package-
private,whichallowsthe Point classtobenonfinalandallows getPoint() tobeinvoked
by classes present within the same package and loaded by a common class loader:
Click here to view code image
Search WWH ::




Custom Search