java 获取 class 的包名称
java get name of package of class
我有一堆小服务,方便地称为微服务 ;-),它们都具有相同的启动行为。它们被安排成包 - 每一个服务一项。包命名是这样的:
com.foo.bar.Application
其中 com.foo 是域部分,bar 是实际的服务名称,Application 是我的主实例 class 和 main 方法。
现在我想做的是在它们启动时打印出标准化的日志消息,显示 URL 用户可能会查询以获取有关服务的一些信息。根据定义,获取服务信息的 URL 应像这样构建:
IP:PORT/bar/admin/info
我尝试使用 getClass()... 等方法获取此 bar.name,但这不起作用。所以我尝试了这个:
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];}
但是您可能已经猜到了,打印出来的内容太多了:
class com.foo.bar.Application
我想得到的是
bar
我怎样才能做到这一点???
顺便说一句,我正在使用 Java 8 和 Spring 启动 - 如果有帮助的话
此致,
克里斯
像这样:
String pack = getClass().getPackage().getName();
String[] split = pack.split("\.");
pack = split[split.length-1];
您可以尝试先从 class 中检索包对象,然后读取其名称。以下代码将在 packageName
变量中为您提供完整的包含包名称(例如 "com.foo.bar"),并在 directParent
中提供直接父名称(例如 bar
)变量:
String packageName = getMyClass().getPackage().getName();
String directParent;
if(packageName.contains(".")) {
directParent = packageName.substring(1 + packageName.lastIndexOf("."));
} else {
directParent = packageName;
}
因此,如果将这些变量放在此代码段之后,您的日志语句可以只使用这些变量之一。
感谢 Ernest 的提示,它完美无缺。
对于可能有相同要求的所有其他人,我将 post 我的代码如下:
@ComponentScan(basePackages = "com.foo.fileexportservice")
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, LiquibaseAutoConfiguration.class})
@EnableEurekaClient
@EnableCircuitBreaker
@EnableFeignClients(basePackages = "com.foo.fileexportservice")
public class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
private static final String ERROR_MSG = "You have misconfigured your application! ";
@Inject
private Environment env;
/**
* Main method, used to run the application.
*/
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(true);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
addDefaultProfile(app, source);
Environment env = app.run(args).getEnvironment();
LOG.info("Access URLs:\n----------------------------------------------------------\n" +
"\tLocal: \t\thttp://127.0.0.1:{}/" + getPackageName() + "/admin/info\n" +
"\tExternal: \thttp://{}:{}/" + getPackageName() + "/admin/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
*/
private static final String getPackageName() {
String packageName = getMyClass().getPackage().getName();
String directParent;
if(packageName.contains(".")) {
directParent = packageName.substring(1 + packageName.lastIndexOf("."));
} else {
directParent = packageName;
}
return directParent;
};
private static final Class[] getClassContext() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext();
};
private static final Class getMyClass() { return getClassContext()[2];}
/**
* If no profile has been configured, set by default the "dev" profile.
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active") &&
!System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
}
我有一堆小服务,方便地称为微服务 ;-),它们都具有相同的启动行为。它们被安排成包 - 每一个服务一项。包命名是这样的:
com.foo.bar.Application
其中 com.foo 是域部分,bar 是实际的服务名称,Application 是我的主实例 class 和 main 方法。
现在我想做的是在它们启动时打印出标准化的日志消息,显示 URL 用户可能会查询以获取有关服务的一些信息。根据定义,获取服务信息的 URL 应像这样构建:
IP:PORT/bar/admin/info
我尝试使用 getClass()... 等方法获取此 bar.name,但这不起作用。所以我尝试了这个:
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];}
但是您可能已经猜到了,打印出来的内容太多了:
class com.foo.bar.Application
我想得到的是
bar
我怎样才能做到这一点???
顺便说一句,我正在使用 Java 8 和 Spring 启动 - 如果有帮助的话
此致,
克里斯
像这样:
String pack = getClass().getPackage().getName();
String[] split = pack.split("\.");
pack = split[split.length-1];
您可以尝试先从 class 中检索包对象,然后读取其名称。以下代码将在 packageName
变量中为您提供完整的包含包名称(例如 "com.foo.bar"),并在 directParent
中提供直接父名称(例如 bar
)变量:
String packageName = getMyClass().getPackage().getName();
String directParent;
if(packageName.contains(".")) {
directParent = packageName.substring(1 + packageName.lastIndexOf("."));
} else {
directParent = packageName;
}
因此,如果将这些变量放在此代码段之后,您的日志语句可以只使用这些变量之一。
感谢 Ernest 的提示,它完美无缺。 对于可能有相同要求的所有其他人,我将 post 我的代码如下:
@ComponentScan(basePackages = "com.foo.fileexportservice")
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, LiquibaseAutoConfiguration.class})
@EnableEurekaClient
@EnableCircuitBreaker
@EnableFeignClients(basePackages = "com.foo.fileexportservice")
public class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
private static final String ERROR_MSG = "You have misconfigured your application! ";
@Inject
private Environment env;
/**
* Main method, used to run the application.
*/
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(true);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
addDefaultProfile(app, source);
Environment env = app.run(args).getEnvironment();
LOG.info("Access URLs:\n----------------------------------------------------------\n" +
"\tLocal: \t\thttp://127.0.0.1:{}/" + getPackageName() + "/admin/info\n" +
"\tExternal: \thttp://{}:{}/" + getPackageName() + "/admin/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
*/
private static final String getPackageName() {
String packageName = getMyClass().getPackage().getName();
String directParent;
if(packageName.contains(".")) {
directParent = packageName.substring(1 + packageName.lastIndexOf("."));
} else {
directParent = packageName;
}
return directParent;
};
private static final Class[] getClassContext() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext();
};
private static final Class getMyClass() { return getClassContext()[2];}
/**
* If no profile has been configured, set by default the "dev" profile.
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active") &&
!System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
}