One Two Three
One Two Three

Reputation: 23497

set a (method) breakpoint for a particular object (and not all instances of that type) in java

Suppose I have a class

public class Foo
{
     public void doThing() { ...}
}

Say I have a lot instances of Foo, but I'm only particularly interested in one of them.

How would I "tag" that instance and set a "conditional breakpoint" in doThings that would stop ONLY for the tagged instance? Is there a "builtint" way, particularly by the Eclipse debugger, to do this?

Currently, I have to manually create a boolean flag in the Foo class setting it to false by default, and create a conditional breakpoint based on that in doThings. Then when I encounter the interested object, I would set the flag to true by executing the setter code in the Display window.

But clearly, that requires modifying the code and adding some boilerplate, which is not always possible or a good thing to do.

Upvotes: 12

Views: 2269

Answers (3)

Willian
Willian

Reputation: 522

Yes, there is instance breakpoints in Eclipse.

You have to put a common breakpoint in the desired class and, in the variables panel, you right-click on the instance and choose Instance Breakpoints.

Instance Breakpoints

A popup will ask you which breakpoint you want to active for that instance.

Popup Selection

You choose and it's done!

Done

Upvotes: 9

M A
M A

Reputation: 72844

Not the cleanest way, but you can set a conditional breakpoint on the default Object#toString output of the instance.

After getting the default toString() result of the instance, add something like the following as a breakpoint condition in the doThing method:

this.toString().equals("Foo@184ec44")

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500225

I don't know of any "proper" way, but one approach would be to call hashCode() in the watch window when you first create it, and then make the breakpoint conditional on the hashCode() as well. So you'd need to change the break point each time you ran it - somewhat annoying, but it does at least give you a constant value that you can use to refer to the object. (That's assuming the class doesn't override hashCode(), of course - if you've got many instances with the same hash code, that makes things trickier.)

Upvotes: 1

Related Questions