Java Reference
In-Depth Information
newly compiled classes, it won't work for the previous example. Jdb refuses to redefine
classes that have multiple versions loaded, because it can't determine which version
should be redefined. But what about Eclipse? Can it help you update the right version
of DefaultShape ?
HOTSWAP WITH ECLIPSE
In the previous section, you successfully used the Eclipse debugger to manage multiple
versions of source code while debugging. Will Eclipse come to the rescue again and let
you fix the broken DefaultShape implementation while leaving earlier working ver-
sions intact? If you still have the Eclipse debugger instance running, you can skip to the
next paragraph. Otherwise, you need to relaunch the example by clicking the drop-
down arrow next to the bug icon (circled in figure 8.2) and selecting ch8_debugging_
example. Trigger the exception again by attempting to paint a shape.
Yo u s h o u l d h a v e t h e p a i n t e x a m p l e s u s p e n d e d i n t h e d e b u g g e r a t t h e p o i n t o f f a i l u r e ,
as you saw in figure 8.5. Unlike jdb, which has to be told which classes to redefine, the
Eclipse debugger automatically attempts to redefine any class whose source changes in
the IDE (provided you have automatic builds enabled). This means all you need to do
to squish this bug is change the setColor() method in the open DefaultShape.java win-
dow so that m_shape is initialized before you use it, and save the file. For a quick solution,
you can copy and paste the relevant code from the draw() method, as follows.
Listing 8.2 Fixing the setColor() method
public void setColor(Color color) {
if (m_context != null) {
try {
if(m_shape == null) {
m_shape = (SimpleShape) m_context.getService(m_ref);
}
m_shape.setColor(color);
} catch (Exception ex) {}
}
}
Copying code this way is fine for a quick debugging session, but it's better to extract
the initialization code into a common method for use by both the draw() and set-
Color() methods. Reducing code duplication makes testing and debugging a lot eas-
ier. For now, you'll keep things simple: paste the code from listing 8.2 over the broken
setColor() implementation. When you're ready, click Save to squish the bug!
What happened? Most, if not all, of you got an error message like the one in fig-
ure 8.6, saying the JVM couldn't add a method to an existing class. This happened
because Eclipse tried to update both versions of the DefaultShape class. Although it
was able to redefine the broken setColor() method in the version from this chap-
ter, there is no such method in the DefaultShape class from chapter 4. Instead, the
debugger attempted to add the setColor() method to the old class, but adding
methods isn't supported by the current Sun implementation of HotSwap. Even
 
Search WWH ::




Custom Search