Souvik De
Souvik De

Reputation: 70

Dynamic Class in Java

I am trying to build a simple class that when extended gives a class two functions, save() & read(). This class will serialize the subclass and store it in a .ser file. and also deserialize it and restore the state.

I am thinking of using a builder for initializing the subclass. With this, the class will always start with the previous state or make a new state if required.

Todo x = new Todo().Builder().className(Todo.class).build();

The save() function is working just fine.

    public void save(String fileName) {
        try {
            fout = new FileOutputStream(fileName+".ser");
            out = new ObjectOutputStream(fout);

            out.writeObject(this);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

In the Builder() function where I am taking the Todo.class as a parameter I am using Class<?> className but now I am not able to figure out what I have to do.

Builder function I want to load the object of the class and return it. An in the read function I want to update the state of the class.

Upvotes: 0

Views: 48

Answers (1)

Joni
Joni

Reputation: 111219

ObjectInputStream creates and returns a full object, I don't know how you want to combine that with your builder idea. Here's a simple method to read an object of an arbitrary class from a file:

    public static <T> T read(String fileName, Class<T> klass) throws IOException, ClassNotFoundException {
        Path filePath = Path.of(fileName);
        try (ObjectInputStream objectInputStream = new ObjectInputStream(Files.newInputStream(filePath))) {
            return klass.cast(objectInputStream.readObject());
        }
    }

Upvotes: 1

Related Questions