This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Problem (?) with newInstance Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Reply Bookmark "Problem (?) with newInstance" Watch "Problem (?) with newInstance" New topic
Author

Problem (?) with newInstance

Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 8438

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.


[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
Nathan Pruett
Bartender

Joined: Oct 18, 2000
Posts: 4121

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.


-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 8438

Thanks Nat.
Got it now.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Problem (?) with newInstance
 
Similar Threads
object creation in GC
Trouble printing out the indecies of a array.
Art and Science of Java Chapter 4 Exercise 7
Still having some trouble with Observer/Observable
Hundred part a