I want to know how deserilize a class who contain staic attributes from file because when I create an instance from project , I can't affect it to the global class
My Code : ( deserialize method doesn't work )
public class Project implements Serializable{
private static String name;
private static String site;
private static Table table;
public static String getName() {
return Project.name;
}
public static void setName(String name) {
Project.name = name;
}
public static String getSite() {
return Project.site;
}
public static void setSite(String site) {
Project.site = site;
}
public static Table getTable() {
return Project.table;
}
public static void setTable(Table table) {
Project.table = table;
}
// Serialize
public static boolean serialize(String path){
try{
FileOutputStream fout = new FileOutputStream(path);
Crypto.encrypt(Project.class, fout);
return true;
}catch(Exception ex){
return false;
}
}
public static boolean deserialze(String path){
try{
FileInputStream fin = new FileInputStream(path);
Project project = (Project) Crypto.decrypt(fin);// decrypt file
Project.name = project.getName();
Project.site = project.getSite();
Project.table = project.getTable();
return true;
}catch(Exception ex){
return false;
}
Serialization works with objects — instances of classes. But static fields aren't part of an instance. So serialization doesn't touch them.
You're not actually serializing an instance of your Project class, though. You're serializing the class object itself, which is an instance of the java.lang.Class class. I can see why you'd think that might store your static fields, but it doesn't: a class object is for reflection, getting information about the class. It doesn't actually hold the class's data; the static fields in the class are not fields of the Project.class object. AFAIK, serializing a class object is generally not a useful thing to do.
Your fields look like they probably shouldn't be static anyway, because they hold information that should be different for each project. Right now, you have a single name that's shared across all projects, and a single site, and a single table. You could run new Project() fifty times and have fifty distinct objects, but there's no way to make them different from each other. Your program has no way to represent two projects with different names.
My advice: take out all the static keywords, change your static field references (e.g. Project.name) to instance field references (e.g. this.name), create an instance of your class (e.g. Project project = new Project()) and set its fields, and serialize that.
If you're going to implement java.io.Serializable interface remember that when you deserializing transient or static fields they most likely gonna have default value (null for Object types).
Static field also get default value if there are no objects in the scope (otherwise it get initialized with the value that is defined for an existing object).
Related
I have a problem with serialization of a class using the singleton pattern. First let me introduce the code:
import java.io.ObjectStreamException;
import java.io.Serializable;
import org.ejml.simple.SimpleMatrix;
public class Operation implements Serializable {
private static final long serialVersionUID = 1L;
private final static int CONSTANT = 10;
private SimpleMatrix data;
private Long timestamp;
private static Operation instance = new Operation ();
private Operation () {
data = new SimpleMatrix(1, CONSTANT);
}
protected static Operation getInstance() {
return instance;
}
//Hook for not breaking the singleton pattern while deserializing.
private Object readResolve() throws ObjectStreamException {
return instance;
}
protected void setData(SimpleMatrix matrix) {
this.data = matrix;
}
protected SimpleMatrix getData() {
return data;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
I have three problems with it hoping that somebody can help me:
As far as I know, static fields are no serialized. So if I deserialize is my final static field CONSTANT set to 10? If not, how can I make this? This is very important.
As you can see, in the constructor a new matrix is created. If I deserialize, is my data overwritten by this constructor? For deserialization I want the data of the serialized version and not a new matrix. The constructor I only need the first time before serialization to instantiate the object.
Before I serialize I will set the field timestamp to the time of serialization. After deserialization I would like to compare this field with the timestamp of some files (to see if files have changed since serialization). What sort of timestamp should I use for both the serialization time and the last modified time of files so that I can easily compare?
The static constant is associated with the class, so serialization and deserialization of your instance won't impact it at all.
For the deserialization to work, you need to set the singleton's data to the deserialized instance data:
private Object readResolve() throws ObjectStreamException {
instance.setData(getData());
return instance;
}
The timestamp can stay as a Long, that's fine. Use System.currentTimeMillis(), you'll be able to compare with a File object lastModified() date. Just set the field when you serialize:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException{
timestamp=System.currentTimeMillis();
out.defaultWriteObject();
}
A test I've made to be sure of what I say, using a String instead of a matrix as in your code:
public static void main(String[] args) throws Exception {
Operation op=getInstance();
op.setData("test1");
byte[] ds=serialize();
System.out.println(new Date(getInstance().timestamp));
op.setData("test2");
deserialize(ds);
System.out.println(getInstance().getData());
}
This gives me the current date and test1, since the deserialize instance has overriden the current instance. serialize and deserialize simply convert between the instance and bytes.
I would suggest that you adopt the Enum Singleton approach for implementing Singletons, as handling Serialization would be done for free. In your case it would be
public enum Operation {
INSTANCE;
// No need to handle Serialization
}
Quoting Joshua Bloch in Effective Java "a single-element enum type is the best way to implement a singleton."
There are plenty benefits to this approach, you can find out here
And also For instance control, prefer enum types to readResolve
I'm using Jackson to deserialize feeds and pull specific values from it. I'm trying to do this without know what feeds will be selected at runtime. I attempted to make a generic class that contains the method for deserializing the feed, and it works oddly enough. The problem is I can't pull any information from it without explicitly stating which class I am pulling from.
public class Motor<T> {
final ObjectMapper jsonMapper = new ObjectMapper();
public Object pullJson( String url, Object blah ) throws IOException{
#SuppressWarnings("unchecked")
T mapped = jsonMapper.readValue(new URL(url), (Class<T>) blah);
return mapped;
}
//Some other code
}
public class Root{
public static String value;
public String getValue(){
return value;
}
}
public class Propeller {
public static void main(String[] args) throws IOException{
Motor<?> motor = new Motor();
List<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(Root.class)
String url = "blah.com/blah.json"
Object blah = classes.get(0);
blah = motor.pullJson(url, blah);
System.out.println(blah.value);
}
}
The only way I could think to pass a class into the method without know what the class will be was to set the class parameter as an Object and then pass a generic class onto it.
If I we're to ask for Root.value, it'll give me value's value, but I won't know what class the method will act on at runtime. And trying to act on the class declared as blah will tell me value cannot be resolved. I have a feeling my thought process here is extremely flawed in trying to pass a class as an object and reading the values that way.
A Piece of important information: The classes are all separate files and there are about 10 beans in total .
I am working on a project with multiple classes through which data must be passed.
I.e. a couple strings from say Class1 must be able to be used in Class2.
My program uses JavaBeans with set and get methods but if I set a bean in one class and try to get that data in another class I just get a null value returned.
I am unsure as to what the best method is, I have the beans nicely defined and would like to keep using them but I do not know how.
Could someone point me in the correct direction or give an example.
Thanks
Edit
Bean class snippet;
public class beans implements java.io.Serializable {
private String string1;
public String getstring1() {
return this.string1;
}
public void setstring1(String string1) {
this.string1 = string1;
}
And the setter code in say class1:
beans bean = new beans();
bean.setstring1("test");
And the class where the bet is "got", class2
beans bean = new beans();
String text = bean.getstring1();
That is pretty much how I am using the beans and they are not working as I want them to.
In your example you are creating a new bean in each class. The first and the second class have references to two different objects, that's why they can't access the same values.
There are multiple ways to solve this and it really depends on your application. But let me suggest one generic solution.
You can create a BeanRepository which is responsible for having references to all bean objects. Other classes then need to know the id of the bean and they can get a reference.
BeanRepository (notice the static methods):
public class BeanRepository {
private static Map<Integer, Bean> beanMap = new HashMap<Integer, Bean>();
public static void putBean(int id, Bean bean) {
beanMap.put(id, bean);
}
public static Bean getBean(int id) {
return beanMap.get(id);
}
}
The bean:
public class Bean {
private String name;
public Bean(String name) {
this.name = name;
}
public String whoAmI() {
return name;
}
}
Classes A and B:
public class ClassA {
private Bean bean;
public ClassA(int beanId) {
this.bean = BeanRepository.getBean(beanId);
}
public void test() {
System.out.println("I am ClassA. You are " + bean.whoAmI());
}
}
public class ClassB {
private Bean bean;
public ClassB(int beanId) {
this.bean = BeanRepository.getBean(beanId);
}
public void test() {
System.out.println("I am ClassB. You are " + bean.whoAmI());
}
}
Test method:
public class Main {
public static void main(String[] args) {
BeanRepository.putBean(1, new Bean("one"));
ClassA a = new ClassA(1);
ClassB b = new ClassB(1);
a.test();
b.test();
}
}
container I am very puzzled by your question. Are you referring to Enterprise Java Beans?
If you just mean ordinary JavaBeans just featuring get and set methods, the first thing I would advise is to learn how to use jUnit. Test your data bean first inorder to ensure it is working as intended.
Beside that if your class live within the same JVA (you only start a single java.exe / run a single application) everything should just work fine.
public class Data {
private String value;
public void set(String value) { this.value = value; }
public String get() { return this.value; }
}
public class ClassA {
Data data = new Data();
ClassA() { data.set("From ClassA"); }
}
public class ClassB {
Data data;
ClassB(Data data) { this.data = data; }
public void print() {
System.out.println(data.get());
}
}
public static void main(String args []) {
new ClassB(new ClassA().data).println();
}
This is a simple example using a data object to pass informations around.
Hope this is what you want to know.
[Update]
After you add some code I see the problem. As other users already wrote you are creating new objects (instances) every time. Since the string1 is a property of that class ever instance of it will have their own value.
The default example is a person. Creating a Person class with a property name (similar to your string1) you can create two persons (instances of class Person). You can now name every person individual.
Thats what Class mean. You specify the properties (instance variables) and behavior (methods) of instances (actual object) of that class.
If you want to share information you need a way to pass(!) an instance (object) of a Class to other instances. In Java different way exist. You can use static variables which are global (bound to the Class instead of an instance of a class), you can use singleton pattern (which employes the static variable), you can use ThreadLocal (a global store limited to the current thread), you may use managers / repositories storing objects and you pass the manager / repository objects along, you can use databases or you can use a dependency injector which is like a transparent object manager. Those are basically it.
For your use case I would use Singleton first.
public class MySingleton {
private static Bean myBean;
public static void setBean(Bean myBean) { MySingleton.myBean = myBean; }
public static Bean getBean() { return myBean; }
}
Using the class is straight forward:
Bean bean = new Bean();
bean.setString1("test");
MySingleton.setBean(bean);
Bean bean2 = MySingleton.getBean();
System.out.println(bean2.getString1()); //prints test
But beware this is the lazy way of doing things. Using static has some draw backs if you have a complex project especially when it comes to serialization, concurrency and reuse.
If you'se serializing/deserializing your classes, make sure that
string fields themselves are not marked as transient.
you're not using custom writeObject(ObjectOutputStream ) methods in your object where you forgot your string fields.
you're not cloning your class with custom clone() methods where you forgot your string field
you wrote setter and getter properly in the first place.
and things shoud work ;)
I want to create something that resembles an extendable Enum (understanding extending Enums isn't possible in Java 6).
Here is what im trying to do:
I have many "Model" classes and each of these classes have a set of Fields that are to be associated with it. These Fields are used to index into Maps that contain representations of the data.
I need to be able to access the Fields from an Class OR instance obj as follows:
MyModel.Fields.SOME_FIELD #=> has string value of "diff-from-field-name"
or
myModel.Fields.SOME_FIELD #=> has string value of "diff-from-field-name"
I also need to be able to get a list of ALL the fields for Model
MyModel.Fields.getKeys() #=> List<String> of all the string values ("diff-from-field name")
When defining the "Fields" class for each Model, I would like to be able to keep the definition in the same file as the Model.
public class MyModel {
public static final Fields extends BaseFields {
public static final String SOME_FIELD = "diff-from-field-name";
public static final String FOO = "bar";
}
public Fields Fields = new Fields();
// Implement MyModel logic
}
I also want to have OtherModel extends MyModel and beable to inherit the Fields from MyModel.Fields and then add its own Fields on top if it ..
public class OtherModel extends MyModel {
public static final class Fields extends MyModel.Fields {
public static final String CAT = "feline";
....
Which woulds allow
OtherModel.Fields.CAT #=> feline
OtherModel.Fields.SOME_FIELD #=> diff-from-field-name
OtherModel.Fields.FOO #=> bar
OtherModel.Fields.getKeys() #=> 3 ["feline", "diff-from-field-name", "bar"]
I am trying to make the definition of the "Fields" in the models as clean and simple as possible as a variety of developers will be building out these "Model" objects.
Thanks
I need to be able to access the Fields from an Class OR instance obj as follows:
MyModel.Fields.SOME_FIELD #=> has string value of "diff-from-field-name"
That is not possible in Java unless you use a real enum or SOME_FIELD is a real field. In either case, the "enum" is not extensible.
The best you can do in Java 6 is to model the enumeration as mapping from String names to int values. That is extensible, but the mapping from names to values incurs a runtime cost ... and the possibility that your code will use a name that is not a member of the enumeration.
The reason that enum types in Java are not extensible is that the extended enum would break the implicit invariants of the original enum and (as a result) could not be substitutable.
I've just tried out some code trying to do what you've just described and it was really cumbersome.
If you have a Fields static inner class somewhere in a model class like this:
public class Model {
public static class Fields {
public static final String CAT = "cat";
protected static final List<String> KEYS = new ArrayList<String>();
static {
KEYS.add(CAT);
}
protected Fields() {}
public static List<String> getKeys() {
return Collections.unmodifiableList(KEYS);
}
}
}
and you extend this class like this:
public class ExtendedModel extends Model {
public static class ExtendedFields extend Model.Fields {
public static final String DOG = "dog";
static {
KEYS.add(DOG);
}
protected ExtendedFields() {}
}
}
then its just wrong. If you call Model.Fields.getKeys() you'd get what you expect: [cat], but if you call ExtendedModel.ExtendedFields.getKeys() you'd get the same: [cat], no dog. The reason: getKeys() is a static member of Model.Fields calling ExtendedModel.ExtendedFields.getKeys() is wrong because you really call Model.Fields.getKeys() there.
So you either operate with instance methods or create a static getKeys() method in all of your Fields subclasses, which is so wrong I can't even describe.
Maybe you can create a Field interface which your clients can implement and plug into your model(s).
public interface Field {
String value();
}
public class Model {
public static Field CAT = new Field() {
#Override public String value() {
return "cat";
}
};
protected final List<Field> fields = new ArrayList();
public Model() {
fields.add(CAT);
}
public List<Field> fields() {
return Collections.unmodifiableList(fields);
}
}
public class ExtendedModel extends Model {
public static Field DOG= new Field() {
#Override public String value() {
return "dog";
}
};
public ExtendedModel() {
fields.add(DOG);
}
}
I wonder whether you really need a generated enumeration of fields. If you are going to generate a enum of a list the fields based on a model, why not generate a class which lists all the fields and their types? i.e. its not much harder to generate classes than staticly or dynamically generated enums and it much more efficient, flexible, and compiler friendly.
So you could generate from a model something like
class BaseClass { // with BaseField
String field;
int number;
}
class ExtendedClass extends BaseClass { // with OtherFields
String otherField;
long counter;
}
Is there a real benefit to inventing your own type system?
I was able to come up with a solution using reflection that seems to work -- I haven't gone through the full gamut of testing, this was more me just fooling around seeing what possible options I have.
ActiveField : Java Class which all other "Fields" Classes (which will be inner classes in my Model classes) will extend. This has a non-static method "getKeys()" which looks at "this's" class, and pulled a list of all the Fields from it. It then checks a few things like Modifiers, Field Type and Casing, to ensure that it only looks at Fields that match my convention: all "field keys" must be "public static final" of type String, and the field name must be all UPPERCASE.
public class ActiveField {
private final String key;
protected ActiveField() {
this.key = null;
}
public ActiveField(String key) {
System.out.println(key);
if (key == null) {
this.key = "key:unknown";
} else {
this.key = key;
}
}
public String toString() {
return this.key;
}
#SuppressWarnings("unchecked")
public List<String> getKeys() {
ArrayList<String> keys = new ArrayList<String>();
ArrayList<String> names = new ArrayList<String>();
Class cls;
try {
cls = Class.forName(this.getClass().getName());
} catch (ClassNotFoundException e) {
return keys;
}
Field fieldList[] = cls.getFields();
for (Field fld : fieldList) {
int mod = fld.getModifiers();
// Only look at public static final fields
if(!Modifier.isPublic(mod) || !Modifier.isStatic(mod) || !Modifier.isFinal(mod)) {
continue;
}
// Only look at String fields
if(!String.class.equals(fld.getType())) {
continue;
}
// Only look at upper case fields
if(!fld.getName().toUpperCase().equals(fld.getName())) {
continue;
}
// Get the value of the field
String value = null;
try {
value = StringUtils.stripToNull((String) fld.get(this));
} catch (IllegalArgumentException e) {
continue;
} catch (IllegalAccessException e) {
continue;
}
// Do not add duplicate or null keys, or previously added named fields
if(value == null || names.contains(fld.getName()) || keys.contains(value)) {
continue;
}
// Success! Add key to key list
keys.add(value);
// Add field named to process field names list
names.add(fld.getName());
}
return keys;
}
public int size() {
return getKeys().size();
}
}
Then in my "Model" classes (which are fancy wrappers around a Map, which can be indexed using the Fields fields)
public class ActiveResource {
/**
* Base fields for modeling ActiveResource objs - All classes that inherit from
* ActiveResource should have these fields/values (unless overridden)
*/
public static class Fields extends ActiveField {
public static final String CREATED_AT = "node:created";
public static final String LAST_MODIFIED_AT = "node:lastModified";
}
public static final Fields Fields = new Fields();
... other model specific stuff ...
}
I can then make a class Foo which extends my ActiveResource class
public class Foo extends ActiveResource {
public static class Fields extends ActiveResource.Fields {
public static final String FILE_REFERENCE = "fileReference";
public static final String TYPE = "type";
}
public static final Fields Fields = new Fields();
... other Foo specific stuff ...
Now, I can do the following:
ActiveResource ar = new ActiveResource().
Foo foo = new Foo();
ar.Fields.size() #=> 2
foo.Fields.size() #=> 4
ar.Fields.getKeys() #=> ["fileReference", "type", "node:created", "node:lastModified"]
foo.Fields.getKeys() #=> ["node:created", "node:lastModified"]
ar.Fields.CREATED_AT #=> "node:created"
foo.Fields.CREATED_AT #=> "node:created"
foo.Fields.TYPE #=> "type"
etc.
I can also access the Fields as a static field off my Model objects
Foo.Fields.size(); Foo.Fields.getKeys(); Foo.Fields.CREATED_AT; Foo.Fields.FILE_REFERENCE;
So far this looks like a pretty nice solution, that will require minimal instruction for building out new Models.
Curses - For some reason my very lengthy response with the solution i came up with did not post.
I will just give a cursory overview and if anyone wants more detail I can re-post when I have more time/patience.
I made a java class (called ActiveField) from which all the inner Fields inherit.
Each of the inner field classes have a series of fields defined:
public static class Fields extends ActiveField {
public static final String KEY = "key_value";
}
In the ActiveRecord class i have a non-static method getKeys() which uses reflection to look at the all the fields on this, iterates through, gets their values and returns them as a List.
It seems to be working quite well - let me know if you are interested in more complete code samples.
There is a specific class in a third party library that I want to serialize. How would I go about doing this?
I'm assuming I will have to write a method that takes in an object of the class and uses reflection to get the private member values. Then for deserialization I would use reflection to put the values back.
Would this work? Is there an easier way?
You could just use a transfer object that implements Serializable, and has the same fields as the third party object. Let the transfer object implement a method that returns an object of the original third party class and you're done:
Pseudocode:
class ThirdParty{
int field1;
int field2;
}
class Transfer implements Serializable{
int field1;
int field2;
/* Constructor takes the third party object as
an argument for copying the field values.
For private fields without getters
use reflection to get the values */
Transfer (ThirdParty orig){
this.field1=orig.field1;
this.field2=orig.field2;
}
ThirdParty getAsThirdParty(){
ThirdParty copy=new ThirdParty();
copy.field1=this.field1;
copy.field2=this.field2;
return copy;
}
/* override these methods for custom serialization */
void writeObject(OutputStream sink);
void readObject(InputStream src);
}
You just have to make sure that the members are serialized correctly if you got any special member objects.
Alternatively if the third party class isn't final you could just extend it, have that implement Serializable and write your own writeObject and readObject methods.
Check here for some serialization infos:
Serialization Secrets - WayBack
Serialization API - Oracle
Serialization Secrets - Old
You need to wrap it into something that does the serialization.
Ideally, the third-party class supports some other form of serialization, for example XML serialization (which is based on bean properties). If not, you have to roll your own. Whether that involves reflection or just getters, setters and constructors depends on the class.
In any case, the wrapper would convert the object into a byte[] or a String or something else and write that into the serialization output. On deserialization it reconstructs the object from that data.
The two methods your wrapper has to implement are
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
A lot depends on the nature of the third party class. Is it final, does it have a no argument constructor, can you construct it given known values or is it constructed by another class, does it itself contain non-Serializable members?
Easiest way is to decompile the class, add an implements Serializable, and recompile it, but if it contains non-Serializable members, things get more complicated.
Another possible solution may be to define a set of private methods inside your Serializable class that uses the instances of the third party class.These special methods are part of a special callback contract the serialization system offers.These methods will be called during the serialization/deserialization process.
Their signatures must be like:
private void writeObject(ObjectOutputStream os) {
// your code for saving the third party variables
}
private void readObject(ObjectInputStream is) {
// your code to read the third party state, create a new ThirdParty instance,
// and assign it to your class.
}
This example clarifies this idea further:
public class MyClass implements Serializable
{
transient private ThirdParty thirdPartyInstance ;
private int myClassVariable ;
private void writeObject(ObjectOutputStream oos)
{
try
{
oos.defaultWriteObject();
oos.writeInt(thirdPartyInstance.getThirdPartyVariable());
oos.writeInt(thirdPartyInstance.getFourthPartyInstance().getFourthPartyVariable());
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void readObject(ObjectInputStream ois)
{
try
{
ois.defaultReadObject(); //the call to defaultReadObject method must always be before any other code in the try block
//Reconstructing thirdPartyInstance
thirdPartyInstance =new ThirdParty(ois.readInt(),new FourthParty(ois.readInt()));
}
catch(Exception e)
{
e.printStackTrace();
}
}
MyClass(int myClassVariable, ThirdParty thirdPartyInstance)
{
this.myClassVariable=myClassVariable;
this.thirdPartyInstance=thirdPartyInstance;
}
ThirdParty getThirdPartyInstance()
{
return thirdPartyInstance;
}
int getMyClassVariable()
{
return myClassVariable;
}
public static void main(String args[])
{
FourthParty fourthPartyInstance=new FourthParty(45);
ThirdParty thirdPartyInstance=new ThirdParty(13,fourthPartyInstance);
MyClass myClassInstance=new MyClass(7,thirdPartyInstance);
System.out.println("Before: ThirdParty variable value is "+myClassInstance.getThirdPartyInstance().getThirdPartyVariable());
System.out.println("Before: FourthParty variable value is "+myClassInstance.getThirdPartyInstance().getFourthPartyInstance().getFourthPartyVariable());
System.out.println("Before: MyClass variable value is "+myClassInstance.getMyClassVariable());
try
{
FileOutputStream fios=new FileOutputStream("D://TestFileq.ser");
ObjectOutputStream oos=new ObjectOutputStream(fios);
oos.writeObject(myClassInstance);
oos.close();
FileInputStream fi = new FileInputStream("D://TestFileq.ser");
ObjectInputStream objectIn = new ObjectInputStream(fi);
MyClass myClassInst = (MyClass)objectIn.readObject();
System.out.println("After: ThirdParty variable value is "+myClassInst.getThirdPartyInstance().getThirdPartyVariable());
System.out.println("After: FourthParty variable value is "+myClassInst.getThirdPartyInstance().getFourthPartyInstance().getFourthPartyVariable());
System.out.println("After:MyClass variable value is "+myClassInst.getMyClassVariable());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class ThirdParty
{
private int thirdPartyVariable;
private FourthParty fourthPartyInstance;
ThirdParty(int thirdPartyVariable,FourthParty fourthPartyInstance)
{
this.thirdPartyVariable=thirdPartyVariable;
this.fourthPartyInstance=fourthPartyInstance;
}
int getThirdPartyVariable()
{
return thirdPartyVariable;
}
FourthParty getFourthPartyInstance()
{
return fourthPartyInstance;
}
}
class FourthParty
{
private int fourthPartyVariable;
FourthParty(int fourthPartyVariable)
{
this.fourthPartyVariable=fourthPartyVariable;
}
int getFourthPartyVariable()
{
return fourthPartyVariable;
}
}
Note that the thirdPartyInstance in MyClass must be declared transient otherwise an exception of type 'java.io.NotSerializableException' occurs.
For more explanation see:
SCJP Sun Certified Programmer for Java 6 by 'Cathy Sierra',Page Number 497