0

I'm trying to make a method in Java that allows me to convert an Object's constructor and the values used in the constructor into a String and convert the String into a method that deserializes the String and converts the String to the selected Object using the newInstance() method in the java.lang.reflect.Constructor class. I want to try an serialize an Object that doesn't implement the Serializable interface.

The way I figured I would do this is using the java.lang.reflect package and making a method that would act as an outside toString() method that takes in an Object and the parameters of the Object in the form of a Class<?>, but I don't know how to recieve the variables used to make the Object. For example, take this User object:

class User {
    private final String username;
    private int userID;
    public User(String username, int userID) {
        if (!validateUserID(userID)) {
            throw new RuntimeException("ID cannot have more or less than 6 digits!" + this.userID);
        }
        this.username = username;
        this.userID = userID;
    }
    private boolean validateUserID(int userID){
        return String.valueOf(userID).length() == 6;
    }
}

If I were to serialize this User object initialized as User user = new User("username", 985313);, I want to get the name of the class, the constructor of the class, the parameters of the class in the form of Class<?>..., and the variables used to initialize this Object. How would I go about doing this?

  • 2
    What you want simply isn't possible. You can't serialize things that aren't serializable in a reliable way. – rzwitserloot Apr 07 '23 at 03:31
  • In a reliable way no. But I have figured out how to do it. I just need to figure out how to make a method that works for any Object. – Alexandrite2000 Apr 07 '23 at 03:50
  • What you can do: you can iterate the fields of the class, and try to serialize them. Those are not necessarily the parameters that you would need for a constructor, however. And you'll have to decide how to deal with reference circles (simplest case: singleton). – Hulk Apr 07 '23 at 04:25
  • 1
    There is a reason java itself basically gave up on the concept of a unified serialization mechanism - it is very hard in general, and can break in subtle ways that are hard to locate and cause bugs later. – Hulk Apr 07 '23 at 04:32
  • 1
    @Alexandrite "I figured out how to solve the world's energy problem. I just need to figure out how to negate gravity". The _just_ part in your question _is_ the hard part. – rzwitserloot Apr 07 '23 at 13:04
  • Does this answer your question? [Converting a String into a Constructor to make a new Object](https://stackoverflow.com/questions/75963002/converting-a-string-into-a-constructor-to-make-a-new-object) – kaqqao Jun 02 '23 at 14:31

0 Answers0