• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problem (?) with newInstance

 
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Nat.
Got it now.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic