dimanche 5 septembre 2021

Why does getClass().getName() work on a module class that is not open?

I have two Java 9 modules, a server, and a handler. The server loads HTTP handlers with the ServiceLoader (code below).

Why does the o.getClass().getName() in this snippet work? Is it because "provided" opens the handler class up to reflection? Does getClass().getName() not use reflection? Does Java somehow always map an interface to the underlying class instance (and thus to the class) without needing reflection?

server module code:

    ServiceLoader
      .load(HTTPHandlerWithContext.class)
      .stream()
      .map(ServiceLoader.Provider::get)
      .forEach(o -> {
        System.out.printf(
          "registering route %s to %s%n",
          o.getContext(),
          o.getClass().getName()
        );
        server.createContext(o.getContext(), o);
      });

handler module-info:

module com.example.helloworld {
  requires com.example.tinyjhttpd;
  requires jdk.httpserver;
  provides com.example.tinyjhttpd.HTTPHandlerWithContext
    with com.example.helloworld.HelloWorld;
}

What I think is the relevant snippet from Class.java was not enough to make it clear to me:

    // Cache the name to reduce the number of calls into the VM.
    // This field would be set by VM itself during initClassName call.
    private transient String name;
    private native String initClassName();




Aucun commentaire:

Enregistrer un commentaire