Actually there is a way to check who called a constructor or method:
by examining the current stack trace.
Not that I'd recommend it, but hey, it works:
public ParkingSlip() {
// get the current stack trace
// element 0: java.lang.Thread.getStackTrace
// element 1: this constructor
// element 2: the class/method calling this constructor
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// verify that it was indeed the ParkingMeter who invoked the constructor
if (!ParkingMeter.class.getName().equals(stackTrace[2].getClassName())) {
throw new IllegalAccessError("Restricted access, only ParkingMeter is allowed to create instances");
}
}
A cleaner solution, which resticts constructor access at compile time (the solution above only checks at runtime) is to
- place
ParkingMeter
and ParkingSlip
(only those two) in a dedicated package
- leave both classes
public
- make the constructor(s) for
ParkingSlip
'friendly' (neither private
, nor protected
, nor public
)
This ensures that the ParkingSlip
constructors can only be accessed by classes in the same package, and as ParkingMeter
is the only other class in that package, you've got what you want.
public class ParkingSlip {
// 'friendly' constructor
ParkingSlip() {
}
}