简体   繁体   中英

Can I see default constructor call Once object is creating | in java

Just a public class A that will have the default constructor defined by JVM and going to call at run time

public class A {

}

Main class has main method which will create the object of class A and automatically call the default constructor of the class A.

public class Main {
    public static void main(String[] args) {
        A a = new A();
    }
}

Is it possible for me to do the debug and can see the cursor flow that end-up into calling default constructor of class A?

There will be no use of debug unless you have some business logic inside. Otherwise it is empty.

But Yes you can.

public class A {

    /* Default no arg constructor */
    public A(){
       System.out.println("Put a break point at this line");
     }
    }

You can still able to run this code without default constructor where JVM internally inserts it.

If you want to add some functionality to, you need to write it manually.

There is no direct way.

You can define the default constructor and print something into it.

class A {
  public A() {
    System.out.println("constructor is called");
  }
}

Now when you create an instance of A class in Main class, the message will be printed. You can put the debug point into the print statement and see the runtime cursor coming at it.

Why would you even want to do this? As the jls states:

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

So there's nothing interesting to see. Just some calls of the default-constructors up to Object . As for the debugging-question, this is highly dependant upon the debugger you use.

Since the default constructor is empty by definition, putting code inside it like some answers suggested makes no sense: it won't be a default constructor anymore.

I don't have an IDE with me now (on the phone), but I think you should be able to step into the default constructor from a statement that creates a new instance of the class, for example, from a line like this:

Something something = new Something();

However, what's the point? The default constructor is empty, so there's nothing to see or debug.

If you want to stop execution when an instance of the class is created by the default constructor, then create a parameterless constructor with a dummy statement in it. (Of course, it won't be, there won't be a default constructor anymore, as noted earlier.)

If you cannot edit the source code of the class, then I don't know how to stop execution in the default constructor. I'd be very interested to learn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM