RFR: 6521141: DebugGraphics NPE @ setFont(); [v4]

Phil Race prr at openjdk.org
Thu Jul 28 18:15:21 UTC 2022


On Thu, 28 Jul 2022 18:08:31 GMT, Tejesh R <tr at openjdk.org> wrote:

>> `DebugGraphics` class has a Graphics instance which is been used in slowed down drawing. The `graphics` object is not initialized anywhere inside the class, where it is expected to set explicitly by the user. When the user doesn't set it and try to use the any mehtods like `drawing/setFont`, NPE is raised which is expected. The scenario is taken care by checking if the `graphics` object is null before using it inside the class, thus eliminating the NPE case.
>
> Tejesh R has updated the pull request incrementally with one additional commit since the last revision:
> 
>   Removed whitespace error

You wrote " The graphics object is not initialized anywhere inside the class, where it is expected to set explicitly by the user. "

which reads a bit like if the user does
DebugGraphics dg = new DebugGraphics();
they must then follow it up with
dg.setGraphics(g);
however there's no such method.

So any DebugGraphics created this way is useless.
You can't use it for debugging 
Making it protected won't prevent mis-use.
Someone could subclass and provide a public no-args constructor and the problem will recur.

The javadoc for the class says :
DebugGraphics objects are rarely created by hand

So likely no one should be doing this.

I'd just add javadoc saying "This constructor should not be called by applications, it
is for internal use only. When called directly it will create an un-usable instance".

The only other thing I can think of is to try to figure out by using
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StackWalker.html#getCallerClass())

if it was called from outside DebugGraphics, and if so install some other graphics instead.

something like .. 
if (graphics == null && stackWalker.getCallerClass() != this.class ) {
   BufferedImage bi = new BufferedImage(1,1,BufferedImage.TYPE_INT_RGB);
   graphics = bi.createGraphics();
}

-------------

PR: https://git.openjdk.org/jdk/pull/9673



More information about the client-libs-dev mailing list