title: java get name of package of class
body: <p>I have a bunch of little services, conveniently called Microservices ;-), that all have the same startup behavior. They are arranged in packages - each one for one service. The package naming is like this:</p>
  
  <pre><code>com.foo.bar.Application
  </code></pre>
  
  <p>where com.foo is the domain part, bar is the actual service name and Application is my main instance class with the main method. </p>
  
  <p>Now what I would like to do is print out a standardized log message when they are started, showing the URL a user may query to get some information on the service.  Per definition the URL to get infos for the service shall be constructed like this:</p>
  
  <pre><code>   IP:PORT/bar/admin/info 
  </code></pre>
  
  <p>I tried to get this bar.name with getClass()... and the like, but that does not work. So I tried this:</p>
  
  <pre><code>LOG.info("Access URLs:\n----------------------------------------------------------\n" +
              "\tLocal: \t\thttp://127.0.0.1:{}/" + getMyClass() + "/info\n" +
              "\tExternal: \thttp://{}:{}/" + getMyClass() + "/info\n----------------------------------------------------------",
                  env.getProperty("server.port"),
                  InetAddress.getLocalHost().getHostAddress(),
                  env.getProperty("server.port")
          );
  
   /**
       * Get the name of the application class as a static value, so we can show it in the log
       */
      public static final Class[] getClassContext() {
          return new SecurityManager() {
              protected Class[] getClassContext(){return super.getClassContext();}
          }.getClassContext();
      };
      public static final Class getMyClass() { return getClassContext()[2];}
  </code></pre>
  
  <p>But as you may already have guessed, this prints out far too much:</p>
  
  <pre><code>class com.foo.bar.Application
  </code></pre>
  
  <p>Where all I'd like to get is</p>
  
  <pre><code>bar
  </code></pre>
  
  <p>How can I achieve this???</p>
  
  <p>By the way, I'm using Java 8 and Spring boot - if that helps</p>
  
  <p>Best regards,</p>
  
  <p>Chris</p>