Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java获取类的包的名称_Java_Spring_Logging_Packages_Classname - Fatal编程技术网

java获取类的包的名称

java获取类的包的名称,java,spring,logging,packages,classname,Java,Spring,Logging,Packages,Classname,我有很多小服务,方便地称为微服务;-),都有相同的启动行为。他们被安排在包中-每一个服务。包命名如下所示: com.foo.bar.Application IP:PORT/bar/admin/info String pack = getClass().getPackage().getName(); String[] split = pack.split("\\."); pack = split[split.length-1]; 其中com.foo是域部分,bar是实际的服务名称,A

我有很多小服务,方便地称为微服务;-),都有相同的启动行为。他们被安排在包中-每一个服务。包命名如下所示:

com.foo.bar.Application
   IP:PORT/bar/admin/info 
String pack = getClass().getPackage().getName();
String[] split = pack.split("\\.");
pack = split[split.length-1];
其中com.foo是域部分,bar是实际的服务名称,Application是我的主实例类和main方法

现在,我想做的是在它们启动时打印出一条标准化的日志消息,显示用户可以查询的URL,以获取有关服务的一些信息。根据定义,获取服务信息的URL应如下构造:

com.foo.bar.Application
   IP:PORT/bar/admin/info 
String pack = getClass().getPackage().getName();
String[] split = pack.split("\\.");
pack = split[split.length-1];
我尝试使用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
我怎样才能做到这一点

顺便说一句,我正在使用Java8和SpringBoot——如果有帮助的话

致以最良好的祝愿

克里斯

像这样的人:

com.foo.bar.Application
   IP:PORT/bar/admin/info 
String pack = getClass().getPackage().getName();
String[] split = pack.split("\\.");
pack = split[split.length-1];

您可以尝试先从类中检索包对象,然后读取其名称。以下代码将在
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的提示,它工作得非常完美。 对于可能有相同要求的所有其他人,我将在下面发布我的代码:

@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);
        }
    }
}

可以返回null。在这种情况下,您只需解析完全限定的类名。@ernest_k完美的答案!