Writing a whole class instance to a file
Is it possible to write an intance of a class to a file whole?
My problem is as follows I have a complicated class system for the piece of software i am currently writing this has vector classes upon vector classes upon vector classes etc. The top class is called rulelist. Having created an instance of this class in the main method and added various instances of other classes to it i want to be able to save this instance on exiting the program. I know how to write individual pieces of data to a file but is there an easier way to do this than to save all the data individualy and then re-sort it out when loading the instance again?
Please help
Will
Sun has some tech tip articles on serialization:
http://developer.java.sun.com/developer/JDCTechTips/
Do a search for 'serialization' on this webpage.
Similar Messages
-
Calling functions of the inner class in .java code file
Hello,
I created a .java code file in Visual J#.Net and converted it into
the application by adding the "public static void main(String args[])"
function.
I have created the two classes one extends from Applet, and the other
extends from Frame. The class which I inherited from the Frame class becomes
the inner class of the class extended from the Applet. Now How do I
call the functions of the class extended from Frame class - MenuBarFrame
class. the outline code is
public class menu_show extends Applet
------init , paint action function---------
public class MenuBarFrame extends Frame
paint,action function for Menu
public static void main(String args[])
applet class instance is created
instance of frame is created
Menu , MenuBar, MenuItem instance is created
and all these objects added
I have Created MenuBarFrame class instance as
Object x= new menu_show().new MenuBarFrame
????? How to call the functions such as action of MenuBarFrame class - what
should be its parameters??????
}Here's how I would do it:
interface Operation {
public int op(int y);
class X {
private int x;
public X(int x) {
this.x = x;
private class Y implements Operation {
public int op(int y) {
return x+y;
public Operation createOperation() {
return new Y();
public static void main(String[] args) {
X app = new X(17);
Operation f = app.createOperation();
System.out.println(f.op(-11));
}Your code, however, has some serious "issues". You typically don't
instantiate an applet class -- that's the job of the applet viewer or Java plugin
your browser is using. If you instantiate the applet directly, you're going
to have to supply it an AppletStub. Do you really want to go that way?
Again, use an applet viewer or browser, or better yet, why write applets at all? -
Passing a binary file to class outputing a compressed file
Hi,
Am i writing a program which gets passed a file to encode via "java compressor < <filename>".
Compressor is a class with main method.
what i have right now is simply:
public class Compressor {
* @param args the command line arguments
public static void main(String[] args) {
InputStream in = new FileInputStream ("");
File f = new File ("");
ByteArrayOutputStream out = new ByteArrayOutputStream (f.length());
int i;
while ((i = in.read()) != -1) {
out.write(i);
in.close();
byte[] result = out.toByteArray();
for (int j = 0 ; i < result.length ; j++) {
byte a = result[j];
} The program is suppose to read the input one byte at a time and treats each one as an instruction which encodes byte compressoring the file and finally outputing this newly compressed file. I'm not sure how the main method will take the filename i.e "java compressor examplefile", any guidance would help greatly.
Thanksin the case above, the command line arguments are passed in the aaaaaaaaaaaaaaaaaaaaaaarggggggggggs array
you probably want aaaaaaaaaaaaaaaaaaaaaaarggggggggggs[0] for the filenameAm not sure i understand, do you mean i must change the param of the main method to String[] args[0] as this resulted in error when i did so. Or do you mean at command line instead file simply being passed to the Compressor program as
"java Compressor < examplefilename"
It has to be "java Compressor < examplefilename[0]" ?
If you could expand on this, would be grateful,
Thanks. -
Getting Class instance of a class
Dear Friends,
I need to get Class instance of a class in my project. Inorder to use the reflection API 's the package name of the class is needed , but it may not be available Only available thing is the name of the class file and the location where that file is existing .
Please suggest some method to get Class instance in this situation.
Shaiju.PYou can create a ClassLoader of your own. There's a simplified example in this thread (reply number 6):
http://forum.java.sun.com/thread.jsp?thread=538836&forum=31 -
Store Class-Properties in XML-File
Hello,
I want to store the properties of my class instances into a XML-File to save and reload the parameters.
My Class to be stored and reloaded:
public class MyData{
public String val1,val2;
public Result(String val1,String val2){
val1=_val1;
val2=_val2;
My working code:
public void save(Vector myDatas){
// myDatas is a Vector of MyData Instances
// write all MyDatas into File /tmp/myData.xml
public Vector load(){
Vector myDatas=new Vector();
// read MyDatas from File /tmp/myData.xml
// and store into myDatas
return myDatas;
}Hi,
the structure is not very interesting because I'm flexible :-)
But for excample like this:
<MyData>
<val1>abc</val1>
<val2>def</val2>
</MyData>
<MyData>
<val1>uvw</val1>
<val2>xyz</val2>
</MyData>
To write such a file is not really the problem. But I don't want to parse the XML structure with String command.
Thanks,
Armin -
Referring to primary Class' instance...
I'm using Flash Develop. Creating a new project creates a Main.as class. How do I refer to the instance of that class from a different file?
Well, there's more than one way. But as an example consider this:
class Main:
package
import flash.display.MovieClip;
public class Main extends MovieClip
private var t:Test;
public function Main()
t = new Test();
addChild(t);
public function traceTest():void
trace("hello world");
Within main we make an instance of the Test class - a simple red rectangle Sprite.
Now in Test:
package
import flash.display.*;
import flash.events.*;
public class Test extends Sprite
public function Test()
graphics.beginFill(0xFF0000);
graphics.drawRect(0,0,100,50);
addEventListener(Event.ADDED_TO_STAGE, callMain);
private function callMain(e:Event):void
MovieClip(parent).traceTest();
So, as soon as the red rectangle is added to the stage, callMain is fired which simply calls traceTest within its parent container. And you will see 'hello world' in the output panel. -
Creating custom class instances for XML nodes
Hi guys,
I'm trying to load an external XML document in my application
and create an instance of a custom class for each node in the XML
based on the value of some of their elements. The instances created
will eventually end up in a DataGrid by the way. The problem I'm
having is there seems to be many ways of doing small parts of this
and I have no idea how to make them all gel. Initially I'm using
HTTPService to load the XML file but I've seen people just use an
XML object. Then, after that, I initially set the loaded XML to an
ArrayCollection but others have used XMLList or XMLListCollection.
I've no idea what's the best way to do this.
Eventually, when I've created all of these instances by
looping over the XML and creating them how will I make them
bindable to the data grid? I'm guessing I'll have to group them
somehow...
Any help would be greatly appreciated. ThanksHey Tracy,
That is exactly what I was talking about in a previous post
you replied to
http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?catid=585&threadid=1344350
Anyhow, Below is some code I created to do what your saying
somewhat dynamically. The idea being you can have many different
object types that you may want to populate with data from XML. In
my case I am using e4x as the result type from my web services. At
present I have about 6 different classes that call this function.
I'd love to get some opinions on the function. Good bad or
???? Any improvements etc????
package . . . .
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import mx.utils.ObjectUtil;
* Utility class to convert xml based Objects to class
instances.
* Takes a value object as the destination and an xmlList of
data
* Look through all the items in the value object. Note we
are using classInfo..accessor since
* our objects are bound all variables become getter /
setter's or accessors.
* Also note, we can handle custom objects, arrays and
arrayCollections.
* History
* 03.11.2008 - Steven Rieger : Created class
public final class XMLToInstance
public static function xmlToInstance( destinationObject :
Object, sourceXMLList : XMLList ) : void
// Get the class definition in XML, from the passed in
object ( introspection so to speak )
var classInfo : XML = describeType( destinationObject );
// Loop through each variable defined in the class.
for each ( var aVar : XML in classInfo..accessor )
// If this is String, Number, etc. . . Just copy the data
into the destination object.
if( isSimple( aVar.@type ) )
destinationObject[aVar.@name] = sourceXMLList[aVar.@name];
else
// Dynamically create a class of the appropriate type
var className : String = aVar.@type;
var ObjectClass : Class = getDefinitionByName( className )
as Class;
var newDestObject : Object = Object( new ObjectClass());
// If this is a custom type
if( isCustomType( className ) && ObjectClass != null
// Recursively call itself passing in the custom data type
and the data to store in it.
// I haven't tested nested objects more than one level. I
suppose it should work.
// Note to self. Check.
xmlToInstance( newDestObject, sourceXMLList[aVar.@name] );
else
// Must be some sort of Array, Array Collection . . .
if( ObjectClass != null )
var anXMLList : XMLList = new XMLList(
sourceXMLList[aVar.@name] );
for each( var anItem : XML in anXMLList )
// I'm sure there are more types, just not using any of them
yet.
if( newDestObject is Array )
newDestObject.push( anItem )
else
newDestObject.addItem( anItem );
// Add the data to the destination object. . . .
destinationObject[aVar.@name] = newDestObject;
} // end function objectToInstance
public static function isSimple( dataType : String ) :
Boolean
* This function is pretty self explanatory.
* Check to see if this is a simple data type. Did I miss
any?
* History
* 03.11.2008 - Steven Rieger : Created function
switch( dataType.toLowerCase() )
case "number":
case "string":
case "boolean":
return true;
return false;
} // end isSimple
public static function isCustomType( className : String ) :
Boolean
* This function is pretty self explanatory.
* Check to see if this is a custom data type. Add them here
as you need. . .
* History
* 03.11.2008 - Steven Rieger : Created function
var aClassName : String = className.replace( "::", "."
).toLowerCase();
aClassName = aClassName.substr( aClassName.lastIndexOf( "."
) + 1, aClassName.length - aClassName.lastIndexOf( "." ) );
switch( aClassName )
case "ndatetimevo":
case "expenselineitemvo":
return true;
return false;
} // end isCustomType
} // end class
} // end package -
Is it possible to make an instance of a class available for
reading / writing to on all documents in an application? If so, how
is it done?
I have an application written that asks a user to login. When
the user enters their information (email / password), information
including their name, email address, date of last login, etc. is
pulled from my database and a class instance is populated on the
current page (lower level page). I would like to reference
different parts of this class instance on multiple documents. For
example, I would like to display a label that has a text property
of "Hello, Jack", where 'Jack' is a variable held in the class
instance on another page at the same level as the current
page.You need to have a look at the Singleton Pattern. Here is a
link that might help you
http://flexrays.wordpress.com/2007/06/20/singleton-pattern/ -
Understanding class "fingerprints" with SWC files
I'm sorry for a very poorly structured question. I just run out of English... I hope one of you guess what's the problem and can provide better words to describe it!
I'm having hard time understanding how classes from SWC files are handled when the app is complied with Flash Builder. We have about 50 SWC files, all compiled from corresponding FLA files. Their libraries contain elements that have AS3 linkages and in the end, there are plenty of classes involved. The classes are packaged in SWC files and Flash Builder finds them just fine. Some AS3 linkages have the same name, which is OK, because they are essentially the same library elements and we don't want to have duplicates in the app. Also plenty of AS3 linkages have same base classes, which means plenty of SWC files carry those base class definitions too, but only one is really needed.
Sometimes everything works, sometimes something breaks. It almost seems like the moon phase affects whether the end result works or not... Sometimes recompiling SWC files helps with one problem, but breaks something else. This leads me to guess, that Flash Builder selects the available classes based on the date of the SWC files? If more than one SWC files have the same class definition, Flash Builder selects the newest?
The error we encounter, is "AS3 Error #1034: Type Coercion failed:", which is related to having one of these shared AS3 linkages (let's say SharedClass) on the timeline of a MovieClip. This means it is *not* created with the new keyword! So if SharedClass is defined in SWC1 and SWC2, maybe Flash Builder decides to use the one from SWC1. This means that elements from SWC2 that use SharedClass will use SWC1's definition of it. But for some reason this doesn't always work as it should. It helped, when I changed how AS3 references the instances declared on the timeline: "var mySharedClassObject:SharedClass" --> "var mySharedClassObject:*" but I don't understand why...
This leads me to believe, that the SharedClass in SWC1 and SWC2 have different "fingerprints" which makes the class casting break in some situations. When I use "new" keyword, everything works, because it doesn't matter which definition will be used. But when the class is created on the timeline, it may require exact fingerprint of that class?
Most of those cases are easily cleaned, but I'm also running into problems with some classes that have only one definition! If the AS3 linkage of SWC1 has the same base class, than AS3 linkage of SWC2, we run into the same problem. This is because both SWC1 and SWC2 contain the definition of the base class and maybe they have different fingerprints, even though our base classes are just AS3 files (no linkages).
Does this make any sense?
Anyone know a way to see the class name collisions and potential problems?If different SWC are using exactly the same class, there’s no problem. If more than one is using the same named class, and the two or more copies are different, they it’s down to the order they get compiled, and that can vary.
Make sure that everywhere that a class has the same name, it’s identical to the other ones. Remember that MovieClips become classes too, so if you have a shared library item named “title”, and it’s different for each SWC because the graphic instead the MovieClip is different, then you’ll get big problems.
One easy solution is to put the classes into a dedicated folder, like:
src/com/yourname/game1/Title.as
and:
src/com/yourname/game2/Title.as
instead of:
src/com/yourname/games/Title.as
You will end up with a lot of identical things in memory, but they have a different path, and won’t clash with each other.
Another thing to know, if you use GetDefinitionByName(“class1”), the main document class needs to know about those classes. This will solve that problem:
public var namedClasses:Array = [class1,class2,class3];
Then when the compiler is doing its thing, it doesn’t go into shock when an embedded SWC is creating an instance of a class from the shared name.
So, make sure things are truly identical, or make sure they have a different path. -
Any way to for a class instance to ask what its instance name is?
Hey. I have a class which needs to create a movie clip on the
stage. Since each instance of the class will only ever have 1 movie
clip on the stage at a time, it seems reasonable that I have the
instance create a movie clip with its own name, prefixed with "mc_"
or something of the sort.
Here's where I don't know quite what to do... How do I get at
this information? For instance, when you a dealing with an XMLNode,
you can simply use...
the_answer = xmlNodeInstance.nodeName;
...I know the analogy fails, but hopefully you know what I'm
looking for.
Thanks!hu....
and when you create your movie clip, (assuming you don't just
build it at authoring time) you specify an instance id through the
createEmptyMovieClip function....
taking a cue from this, I'm guessing that my answer is to
change the structure of what I'm doing a little... instantiate my
object with an instance name as a parameter given to the Class
Constructor... that way the class can have it's own name on file.
I guess my only concern there is how do I keep the "name"
variable from being just completely arbitrary...?
I guess I'm getting away from application (becaust I don't
know when I'd do this...) and into theory.... but for instance,
let's say I create my class like this:
var instanceReference:mySuperCoolClass = new
mySuperCoolClass("instanceName");
So. I have my class instance... ideally, the class would
exist on the stage as "instanceName", with "instanceReference"
being another way to reference the instance. That would be ideal...
but how do I make that happen? Because in the scenario of what I've
just done, I see the class instance existing on the stage as
"instanceReference", and I've just passed it a fun, but meaningless
bit of data called "instanceName"...
I suppose I could have the class go back to "_parent" and
create it's own object.... but here again I'm getting into
territory that feels a lot like i have no idea what I'm doing...
haha!
I guess I have enough info to get back to coding for now...
But I'm deffinately open to more tips... I feel like I'm still
missing how a lot of this works.
(I'm at that awkward place where I can easily explain what
OOP is, but I'm far from experienced in how to implement it... I've
only written about half a dozen classes so far... so I still have a
lot to learn. Thanks for your patience, all of you!) -
Initialize/set a base class from a another base class instance
Hi,
How can I initialize/set a base class from a another base class instance? I do not want to do a copy of it.
It would look something like:
class A {...}
class B extends A
B(A a)
// super = a;
setA(A a)
// super = a;
}Thank you.erikku wrote:
Thanks Winton. It is what I did first but A has lots of methods and if methods are later added to A, I will have to edit B again. For those two reasons, I wanted to use inheritance. The part I was not sure with was the way to initialize B's base (A).You pays your money and you takes your choice. One way (this way) you have to provide forwarders; the other way (inheritance) you have to provide constructors (and if A has a lot of em, you may be writing quite a few).
Ask yourself this question: is every B also an A? No exceptions. Ever.
If the answer is 'yes', then inheritance is probably the best way to go.
However, if there is even the remotest chance that an instance of B should not exhibit 100% of the behaviour of A, now or in the future, then the wrapper style is probably what you want.
Another great advantage of the wrapper style is that methods can be added to A without affecting the API for B (unless you want to).
Winston
PS: If your Class A has a constructor or constructors that take a pile of parameters, you might also want to look at the Builder pattern. However, that's not really what we're talking about here, and it should probably be implemented on A anyway. -
Quick question regarding best practices for class instances.
Is is best to create one class instance and keep a reference to it and reuse that class as needed or should I let that instance be garbage collected and create a new instance as needed?
I have a class in a project that will format and output data to a file. Basically this is recording transactions inputted by the user. I would estimate that this would get called, at the most, 25 times per day.
So is it best to call a new instance or just create one and reuse it?
Thanks,
ton80ton80 wrote:
Quick question regarding best practices for class instances.
Is is best to create one class instance and keep a reference to it and reuse that class as needed or should I let that instance be garbage collected and create a new instance as needed?Reusing or recycling the class (object pooling) may increase performance, but there's a cost associated. Code complexity increases, more code to maintain, etc. And it's doubtful you'll see performance gains. On the other hand, depending on the app, it may yield huge performance gains.
I have a class in a project that will format and output data to a file. Basically this is recording transactions inputted by the user. I would estimate that this would get called, at the most, 25 times per day.
So is it best to call a new instance or just create one and reuse it?Just create the instance inside of a method, each time you need it. At the end of the method, simply let the object fall out of scope. I don't see a case for reuse here whatsoever. -
How to find name of report if I know name of instance and location of instance in Output File Store
Hello all,
can somebody help me to find name of the report if I know name of report instance and also location of instance in Output File Store. It should be done via Query Builder.
It is ...rpt file as output from Crystal Reports. I tried few commands in Query Builder but usually they finished with timeout error.
Could you help me and send specific command? Or way how to change timeout of Query Builder?
Thanks.
matusHello all,
We finally found solution.
We knew that file is located on path .../Output/a_145/009/002/133521/~ce10c.....9332.rtf
This file has more than 2 GB. We tried to find which report is related and provide necessary actions.
As I mentioned we still failed due to timeout error - There was an error retrieving data from the server: CMS operation timed out after 9 minutes.
So we tried to use our testing environment. We started there QueryBuilder and there we successfully tested that we found details about files from FileStore /like Name of the report in Launch Pad, CUID, ...
SELECT SI_NAME, SI_CUID, SI_FILES FROM CI_INFOOBJECTS WHERE SI_FILES.SI_PATH = 'frs://Input/a_148/020/000/5268/'
or
SELECT * FROM CI_INFOOBJECTS WHERE SI_FILES.SI_PATH = 'frs://Input/ a_148/020/000/5268/'
Best regards,
matus -
How do I convert Wallet.class to a CAP file?
I was trying to convert one of the sample files( Wallet.class) to a CAP file but it didn't work.
Please help!!!Please be more specific. Describe what you did in detail, provide outputs of your actions etc. Otherwise noone can help you.
Somebody save the world.. -
How to create java classes when multiple xsd files with same root element
Hi,
I got below error
12/08/09 16:26:38 BST: [ERROR] Error while parsing schema(s).Location []. 'resultClass' is already defined
12/08/09 16:26:38 BST: [ERROR] Error while parsing schema(s).Location []. (related to above error) the first definition appears here
12/08/09 16:26:38 BST: Build errors for viafrance; org.apache.maven.lifecycle.LifecycleExecutionException: Internal error in the plugin manager executing goal 'org.jvnet.jaxb2.maven2:maven-jaxb2-plugin:0.7.1:generate': Mojo execution failed.
I tried genarate java classes from multiple xsd files, but getting above error, here in .xsd file i have the <xe: element="resultClass"> in all .xsd files.
So I removed all .xsd files accept one, now genarated java classes correctly. but i want to genarte the java classes with diffrent names with out changing .xsd
Can you please tell me any one how to resolve this one......
regards
prasad.nadendlaGregory:
If you want to upload several Java classes in one script the solution is .sql file, for example:
set define ?
create or replace and compile java source named "my.Sleep" as
package my;
import java.lang.Thread;
public class Sleep {
public static void main(String []args) throws java.lang.InterruptedException {
if (args != null && args.length>0) {
int s = Integer.parseInt(args[0]);
Thread.sleep(s*1000);
} else
Thread.sleep(1000);
create or replace and compile java source named "my.App" as
package my;
public class App {
public static void main(String []args) throws java.lang.InterruptedException {
System.out.println(args[0]);
exit
Then the .sql file can be parsed using the SQLPlus, JDeveloper or SQLDeveloper tools.
HTH, Marcelo.
Maybe you are looking for
-
Up, Down and hit problem
I created the movie clip and created the bar and clicked inside the library and chose the button. and then I created the new bar inside. and moved the up to down and hit and went back to the normal mode but I saw the first bar without any fill. What
-
Regarding datasource in weblogic server
Hi All, while creating datasource i am getting the following error An error occurred during activation of changes, please see the log for details. weblogic.application.ModuleException: weblogic.common.ResourceException: Could not create pool connecti
-
I am trying to buy panadora and it is saying my apple id has been disabled
I am trying to buy pandora and it is saying my apple id has been disabled. What does that mean?
-
LDAP realm for authentication and ACL in Database
We are thinking of using LDAP realm for authentication and we want to use ACL from a Database. But the documentation says: "WebLogic Server defers to the LDAP realm for authentication, but not for authorization. Authorization is accomplished with acc
-
How to transfer files from imac to macbook air
I recently received my macbook air and I was trying to transfer iWork to my new macbook. Typically, I have no problems in the transfer process when I have done this before from my iMac to my Powerbook. And now, with the Macbook Air, my iMac tells me