• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem (?) with newInstance  RSS feed

 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am working on a distributed system. On the client side, I have a JTabbedPane with around 6 tabs. All of these tabs pull out data from the server and display it.

For optimization purposes, I decided to load the data only while initializing the panels which are displayed as tabs. I declared an array like this

Where A,B,C..N are the panels which I want to display as tabs.

Then I added a ChangeListener to the tabbed pane. On getting change notifications, I am doing something like

I expected this to work fine because from the API documentation of Class#newInstance, it says

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.


To confirm, I had put println statements in all my constructors of A,B,C,..N. I am extremely surprised to see the println invoked every time, where as I was expecting only once.

As a workaround, I did a null check before calling the above code and it works fine .

Where did I go wrong in my approach? I am sure I am missing some basic concept here.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're confusing object initialization with class initialization.

Class initialization means that the class file is loaded into the JVM, the class's static initializer (if one exists) runs, and values of static fields (if any exist) are computed.

newInstance() is like calling a constructor - except through dynamic invocation. Both perform object initialization.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nat.
Got it now.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!