Issue
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:
com.foo.bar.Application
where com.foo is the domain part, bar is the actual service name and Application is my main instance class with the main method.
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:
IP:PORT/bar/admin/info
I tried to get this bar.name with getClass()... and the like, but that does not work. So I tried this:
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];}
But as you may already have guessed, this prints out far too much:
class com.foo.bar.Application
Where all I'd like to get is
bar
How can I achieve this???
By the way, I'm using Java 8 and Spring boot - if that helps
Best regards,
Chris
Solution
You could try retrieving the package object from the class first, then reading its name. The following code will give you the full containing package name (such as "com.foo.bar") in the packageName
variable, and the direct parent name (such as bar
) in the directParent
variable:
String packageName = getMyClass().getPackage().getName();
String directParent;
if(packageName.contains(".")) {
directParent = packageName.substring(1 + packageName.lastIndexOf("."));
} else {
directParent = packageName;
}
So, your log statement could just use one of these variables if you put it after this snippet.
Answered By - ernest_k
Answer Checked By - Willingham (JavaFixing Volunteer)