How to use one type in method?

Tags: ,



I have two forms, one form to create user and one to update user.These forms are similiar and I want to use one type in my method,I wouldn’t like to create two methods one to create user from registerForm and second to create user from updateForm

        private User createUserFromForm( UserRegistrationForm // UserUpdateForm userForm) {
        User user = new User();
        user.setEmail(userForm.getEmail());
        user.setGenderId(genderRepository.findById(userForm.getGenderId()).get());
        user.setName(userForm.getName());
        user.setSurname(userForm.getSurname());
        user.setPassword(passwordEncoder.encode(userForm.getPassword()));
        user.setEnabled(userForm.getEnabled());
        user.setResetPassword(userForm.getResetPassword());
        return user;
    }

Answer

Use generic method like this:

    public class Test {
        
        public static void main(String[] args) {
            System.out.println(createUserFromForm(new UserRegistrationForm()));
            
            System.out.println(createUserFromForm(new UserUpdateForm()));
        }   
        
//The required generic method
        private static <T extends UserForm> User createUserFromForm(T userForm) {
                User user = new User(userForm.getName());
                return user;
         }
        
    }
    
    interface UserForm {
        public String getName();
    }
    
    class UserRegistrationForm implements UserForm {
        @Override
        public String getName() {
            return "John";
        }
    }
    
    class UserUpdateForm implements UserForm {
        @Override
        public String getName() {
            return "John *updated";
        }
    }
    
    record User(String name) {
        public String toString() {
            return name;
        }
    }

Output:

John
John *updated


Source: stackoverflow