...
| Code Block |
|---|
|
// Interface ExceptionReporter
public interface ExceptionReporter {
public void setExceptionReporter(ExceptionReporter er);
public void report(Throwable exception);
}
// Class ExceptionReporters
public class ExceptionReporters implements ExceptionReporter {
public ExceptionReporters(ExceptionReporter er) {
/*/ Carry out initialization */
// incorrectlyIncorrectly publishes the "this" reference
er.setExceptionReporter(this);
}
public void report(Throwable exception) { /* default implementation */ }
public final void setExceptionReporter(ExceptionReporter er) {
//* setsSets the reporter
*/ }
}
// Class MyExceptionReporter derives from ExceptionReporters
public class MyExceptionReporter extends ExceptionReporters {
private final Logger logger;
public MyExceptionReporter(ExceptionReporter er) {
super(er); // callsCalls superclass's constructor
logger = Logger.getLogger("com.organization.Log");
}
public void report(Throwable t) {
logger.log(Level.FINEST,"Loggable exception occurred",t);
}
}
|
...
| Code Block |
|---|
|
public class MyExceptionReporter extends ExceptionReporters {
// ...
public void setReporter(ExceptionReporter er) {
super.setExceptionReporter(this);
}
}
|
In general, detect cases where the this reference can leak out beyond the scope of the current context. In particular, be careful while when using public variables and methods.
...
| Code Block |
|---|
|
public class BadExceptionReporter implements ExceptionReporter {
public BadExceptionReporter(ExceptionReporter er) {
er.setExceptionReporter(new ExceptionReporters(er) {
public void report(Throwable t) {
filter(t);
}
});
}
public void filter(Throwable t) {
//* filtersFilters sensitive exceptions */
}
public void report(Throwable exception) {
/*/ defaultDefault implementation */
}
public void setExceptionReporter(ExceptionReporter er) {
//* setsSets the reporter */
}
}
|
Compliant Solution
| Wiki Markup |
|---|
A {{private}} constructor alongside a {{public}} factory method may be used when it is desired to publish the {{filter()}} method from within the constructor. \[[Goetz 06|AA. Java References#Goetz 06]\] |
...