vendredi 11 septembre 2020

How to find singleton object of class without having reference to it?

Let's consider the following example:

import java.util.Map;
import java.util.Optional;

class Scratch {
    
    private static class UserService {
        
        private final Map<String, String> users = Map.of(
                "user1", "Max", 
                "user2", "Ivan", 
                "user3", "Leo");
        
        public Optional<String> findUserById(String userId) {
            return Optional.ofNullable(users.get(userId));
        }
    }
    
    private UserService getUserService() {
        /// TODO we need to implement it
        return null;
    }

    public void doJobs() {
        // I need to get `userService` here, without explicitly passing it
        // to execute some service method

        UserService userService = getUserService();
        if (userService != null) {
            userService.findUserById("userId");
        }
    }
    
    public void startApplication() {
        UserService userService = new UserService();
        
        doJobs();
    }
    
    public static void main(String[] args) {
        Scratch program = new Scratch();
        program.startApplication();
    }
}

So. we have simple java application without any frameworks, like spring. I need to find UserService object in doJobs() method, without explicitly passing it. Obviously, it is job interview question.

There are the following task preconditions:

  • UserService is not a spring bean or something like this. It is not about DI
  • You cannot explicitly pass UserService object to doJobs() method
  • You cannot set UserService object to some static/global variable/interface/method.
  • You cannot use javaagents.
  • You know, that there is only one object of UserService in current class loader.
  • You may use any reflection (included libraries), if you wish
  • You cannot create new object, you should use existed one

So, generally speaking we need to get somehow list of all objects and find needed one, using knowledge about Class name.

I did not solve this task on job interview. Could you help me to do it?





Aucun commentaire:

Enregistrer un commentaire