aspose file tools*
The moose likes Java in General and the fly likes Passing object from one class to another Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Passing object from one class to another" Watch "Passing object from one class to another" New topic
Author

Passing object from one class to another

Saurabh Pillai
Ranch Hand

Joined: Sep 12, 2008
Posts: 498
I am working on XML file parsing and I am using SAX parser. I have created XMLParser class. In that I have,

and

In CustomDefaultHandler, after parsing, I have stored all data in List of custom objects, now I want this list in my other class to do some business processing and ultimately saving into DB. How can I pass it? The default parse method returns void (understandably). One way I can think of is creating static list object List<CustomObject> customObject in XMLParser class and setting its value in CustomDefaultHandler class.

Thank you.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18155
    
    8

Your CustomDefaultHandler has an instance variable containing a List<Whatsit>, then? If that's what you were saying, then add a method to CustomDefaultHandler which returns that List. Like this:

Then after the parsing is finished (i.e. after the "sp.parse" line of code) you just call that method and you've got your list. Of course you'll have to keep a reference to the CustomDefaultHandler object, rather than just throwing it away like you do, so you can call that method after parsing.
Saurabh Pillai
Ranch Hand

Joined: Sep 12, 2008
Posts: 498
How can it be so simple?

Yeah, it does make sense. You have an instance variable that you want to make available to outside world. Use getter method. Simple! I don't know why it did not occur to me. Thank you Paul.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18155
    
    8

My guess: You were thinking of CustomDataHandler as a class which was doing things, directing the progress of the program. And therefore you wanted to have it direct the end result to your XMLParser class. (Hence your speculations about copying the result to a static variable there.)

Whereas if you think of it as a class whose responsibility is to just do things when it's given little bits of data (which is what a SAX DataHandler really is) then it's obvious that it should also be asked to return the results of what it did.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Passing object from one class to another
 
Similar Threads
Assigning Java variable to javascript variable.
ArrayList of ArrayList<String>
Performance Recommendation for Simple XML Parsing
Custom Struts Tag
JPA and DAO's