I have a class called Flight
The Flight class when instantiated, instantiates another class called SeatingChart, and SeatingChart also instantiates another class and so on and so forth.
public class Flight implements Serializable
{
SeatingChart sc = new SeatingChart(); seating
//WaitingList wl = new WaitingList();
}
public class SeatingChart extends ListAndChart implements PassengerList, Serializable
{
public static final int NOT_FOUND = 42;
Passenger [] pass = new Passenger[40];
}
public class Passenger implements Serializable
{
private String firstName, lastName, fullName;
public String getName()
{
fullName = firstName + " " + lastName;
return fullName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
}
I have another method in another class that deserializes the object saved in the disk
public void actionPerformed(ActionEvent evt)
{
Serialization.deserialize(sw101); <--- sw101 is a Flight object
.
.
.
}
//code for deserialization
public static void deserialize(Flight sw101)
{
String filename = "serialized.ser";
sw101 = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try
{
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
sw101 = (Flight)in.readObject();
System.out.println("sw101" + sw101.toString());
in.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
}
my question is when I assign sw101 the serialized object, everything sw101 instantiated in the beginning like the SeatingChart sc object also get whatever is saved in the file without me doing anything as long as those objects all implement the Serializable interface? If so why is my code not working? what am I doing wrong?
It looks like you're trying to return through a reference parameter (C/C++ background?)
That never works in Java. All parameters (including references) are passed by value. Once you do
sw101=null;
you lose the reference to the object that was passed in.
Your deserialize function should return the flight object instead.
(Technically there is a way to simulate returning through the arguments in Java by using an array, but it leads to unnecessarily complicated code)
In java, all parameters are passed as values.. so the answer to your last question is no. sw101 is a reference to a copy.
As said, you have to return your deserialized object to make it work.
check this article: parameter passing in java
Related
Guys please tell me what is the construction when I call method while creating an object?
for example: Person p = new Person().get.....
If you want to create an Instance of the Object with new and call the Method while creating that Object than you can call that Method in the Constructor of that Objects Class
class Person {
Person() {
method();
}
}
If you create your Object (Person) with this constructor the Method will be invoked.
If you want to call a Method after creating the Object.
Person person = new Person();
String name = person.getName();
or
String name = new Person().getName();
I guess patter Builder is what are you looking for
public class Computer {
//required parameters
private String HDD;
private String RAM;
//optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public String getHDD() {
return HDD;
}
public String getRAM() {
return RAM;
}
public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}
public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}
private Computer(ComputerBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
}
Computer comp = new Computer.ComputerBuilder(
"500 GB", "2 GB").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
The closest thing that comes to mind may be singleton, but it doesn't create new objects. Person p = Person().getInstance()?
I have following class:
public class Owner {
private final Integer id;
private final OwnerType type;
public Owner(Integer iId, Enum eType) {
this.id= iId;
this.lastName = lName;
this.type = eType // how should that work?
}
}
And
public enum OwnerType {
HUMAN,INSTITUTION
}
Which I am calling via:
try {
File file = new File("resources/Owner.txt");
Scanner fileContent = new Scanner(file);
while (fileContent.hasNextLine()) {
String[] person = fileContent.nextLine().split(" ");
this.data.add(new Owner(owner[0],owner[1]));
}
} catch (FileNotFoundException err){
System.out.println(err);
}
Where Owner.txt has a format of:
ID TYPE
Like that:
1 HUMAN
2 INSTITUTION
My question is:
How can I specify the type property of my Owner Object when I am calling the following?
new Owner(owner[0],owner[1])
There are two issues here.
First, the Owner's constructor should receive an OwnerType, not just any Enum:
public Owner(Integer iId, OwnerType eType) {
this.id= iId;
this.type = eType;
}
When parsing the input file, you could use the valueOf method to convert a string value to an OwnerType:
this.data.add
(new Owner(Integer.parseInt(owner[0]), OwnerType.valueOf(owner[1])));
Any Enumeration object have by default the method valueOf(String key), the what this method does is search into all defined values into your enum class and return the right one if find it.
For more info keep on eye on this:
https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf%28java.lang.Class,%20java.lang.String%29enter link description here
In this particular case the enum;
public enum OwnerType {
HUMAN,INSTITUTION
}
if we use OwnerType.valueOf("HUMAN"), will return the enum type HUMAN
Here use this:
try {
File file = new File("resources/Owner.txt");
Scanner fileContent = new Scanner(file);
while (fileContent.hasNextLine()) {
String[] person = fileContent.nextLine().split(" ");
this.data.add(new Owner(person[0],OwnerType.valueOf(person[1])));
}
} catch (FileNotFoundException err){
System.out.println(err);
}
I have a basic name application that is taking in user data from the main class, splits the data in the parser class and then tries to assign everything in the final class and print it out in the toString method. I know the main class and the parser are working fine. I have verified in the parser class that the data DOES split properly and also sends the data through the object I made to the final class to assign it all. However, my final code is returning null..
MAIN CLASS
import java.util.Scanner;
public class MainClass {
public static void main (String[]args)
{
Scanner input = new Scanner(System.in); //create scanner object to gather name information
String fullName = null; //set the predefined value for the users name to null
nameParse splitInformation = new nameParse(); //method build to split the name into different sections
SecondClass access = new SecondClass(); //class built to output the different name data
System.out.println("What is your name?");
fullName = input.nextLine(); //store the users name and pass it into the data parser
splitInformation.parseNameInformation(fullName); //name parsing parameters built
System.out.println(access.toString());
}
}
Data Parser Class
public class nameParse {
private String firstName;
private String middleName;
private String lastName;
public nameParse()
{
firstName = "initial";
middleName = "initial";
lastName = "initial";
}
public void parseNameInformation(String inputInfo)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
SecondClass sendData = new SecondClass();
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}
}
Final Class
__
public class SecondClass {
private String firstName;
private String middleName;
private String lastName;
/*public String GFN()
{
return firstName;
}
public String GMN()
{
return middleName;
}
public String GLN()
{
return lastName;
}*/
public String setFirstName(String yourFirstName)
{
firstName = yourFirstName;
return this.firstName;
}
public String setMiddleName(String yourMiddleName)
{
middleName = yourMiddleName;
return this.middleName;
}
public String setLastName(String yourLastName)
{
lastName = yourLastName;
return this.lastName;
}
public String getFN()
{
return firstName;
}
public String toString()
{
String printNameInfo = "\nYour First Name:\t" + getFN();
return printNameInfo;
}
}
You never set any of your SecondClass object's (called "access") fields, so of course they'll all be null.
So in short, your code creates a nameParse object, gets information from the user, but does nothing with that information. You create a SecondClass object called access, put no data into it, and so should expect no valid data in it when you try to print it out. Solution: put information into your SecondClass object first. Call its setter methods:
// be sure to call the setter methods before trying to print anything out:
access.setSomething(something);
access.setSomethingElse(somethingElse);
Edit
You state:
I thought I set the data using the sendData.setFirstname(...) etc?
In the parseNameInformation method you create a new SecondClass object and you do set the fields of this object, but this object is completely distinct from the one in your main method whose fields are still null. To solve this, give parseNameInformation a method parameter and pass in your main method's SecondClass object into it and set its methods. You'll have to create the SecondClass object before calling the method of course.
i.e.,
public void parseNameInformation(String inputInfo, SecondClass sendData)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
// SecondClass sendData = new SecondClass(); // !!! get rid of this
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}
I am new to Java and encountered this problem: I am learning how to save object state to a file and I got stuck with passing an array to the constructor. I believe that the problem is the base class with the constructor but I am not sure.
here is my Hero class:
import java.io.Serializable;
public class Hero implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int power;
private String type;
private String[] wepons;
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getWepons() {
return wepons;
}
public void setWepons(String[] wepons) {
this.wepons = wepons;
}
public Hero(int powerH, String typeH, String[] weponsH) {
this.power = powerH;
this.type = typeH;
this.wepons = weponsH;
}
}
and here is class which I try to use to save the object state:
import java.io.*;
public class SaveGame {
public static void main(String[] args) {
Hero hero1 = new Hero(50, "Elf", new String[] {"bow", "short sword", "powder"});
try{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser"));
os.writeObject(hero1);
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
ObjectInputStream is;
try {
is = new ObjectInputStream(new FileInputStream("Game.ser"));
Hero p1N = (Hero) is.readObject();
System.out.println(p1N.getPower() + " " + p1N.getType() + " " + p1N.getWepons());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Can you tell me and explain what am I doing wrong. Do I really need setters and getters in my Hero class and I have the feeling that I am using them incorrectly.
My problem was that when I tried to print out the Hero's parameters I got content of the array instead of string representation of the array. Thanks to user2336315 I know now that i should use Arrays.toString method when printing content of an array
I ran your code and everything seems to be fine. The only problem is that you want to print the content of the array itself, not the string representation of the array itself. So use Arrays.toString :
System.out.println(p1N.getPower() + " " + p1N.getType() + " " + Arrays.toString(p1N.getWepons()));
Output :
50 Elf [bow, short sword, powder]
Deserialization mechanism creates the class using its meta data. It does not depend on the access levels of the members of the target class, inclusing constructors. (Your code will work even Hero class has private default constructor.)
I have several pojos whose instance variables need to be converted to Object arrays. I am trying to find a way that this can be handled dynamically instead of adding a toObjectArray() method in each pojo.
Here is a sample class with the toObjectArray() method that I would like to get rid of:
public class Contact {
private String lastName;
private String firstName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Object[] toObjectArray() {
return new Object[] {
this.getLastName(),
this.getFirstName(),
};
}
}
The instance variables do not have to be returned in order. I have a custom annotation which allows me to reflect proper order for the object array. I'm simply wondering if it is possible to dynamically iterate the instance variables and values of an object in order to create an object array.
Something like this...
public static Object[] toObjectArray(Object obj) {
/// cast Object to ?
/// iterate instance variables of Contact
/// create and return Object[]
}
public static void main(String[] args) {
Contact contact = new Contact();
contact.setLastName("Garcia");
contact.setFirstName("Jerry");
Object[] obj = toObjectArray(contact);
}
Any help would be greatly appreciated. Please let me know if I need to be more clear.
Thank you!
One possible way could be using reflection.
static <T> Object[] getFieldValues(final Class<T> type, final T instance) {
final Field[] fields = type.getDeclaredFields(); // includes private fields
final Object[] values = new Object[fields.length];
for (int i = 0; i < fields.length; i++) {
if (!fields[i].isAccessible()) {
fields[i].setAccessible(true); // enables private field accessing.
}
try {
values[i] = fields[i].get(instance);
} catch (IllegalAccessException iae) {
// ##?
}
}
return values;
}
//Creating dyanamic class object[dynamic array] size for Object.
//Defining Testclass for creatring menu buttons
public class TestClass extends AbstractAction{
boolean literal;
public TestClass(String literal) {
super(literal);
}
public void actionPerformed(ActionEvent e) {
}
}
ArrayList<TestClass> ObjectArray= new ArrayList<TestClass>();
//Here ObjectArray is defined as dynamic array class object.
//Insert new Class objects to the ObjectArray
ObjectArray.add( new TestClass("Button1")) ;
ObjectArray.add( new TestClass("Button2")) ;
ObjectArray.add( new TestClass("Button3")) ;
//Converting ArrayList object to ClassObject array
TestClass testclassObject[]=ObjectArray.toArray(new [ObjectArray.size()])
//Using of Class object array
for (TestClass subAction : testclassObject) {
if(subAction != null){
JButton subButton = new JButton ((String)subAction.getValue(Action.NAME), null);
subButton.addActionListener(subAction);
//Adding buttons to JPanel
JPanel buttonpanel= new JPanel();
buttonpanel.add(subButton);
}
}