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?
Aucun commentaire:
Enregistrer un commentaire