简体   繁体   English

java获取类包的名称

[英]java get name of package of class

I have a bunch of little services, conveniently called Microservices ;-), that all have the same startup behavior. 我有一堆小服务,方便地称为Microservices ;-),它们都有相同的启动行为。 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. 其中com.foo是域部分,bar是实际的服务名称,Application是我的使用main方法的主要实例类。

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. 现在,我想做的是在启动时打印出标准的日志消息,显示用户可以查询以获取有关服务的某些信息的URL。 Per definition the URL to get infos for the service shall be constructed like this: 根据定义,获取服务信息的URL的格式应如下所示:

   IP:PORT/bar/admin/info 

I tried to get this bar.name with getClass()... and the like, but that does not work. 我试图用getClass()来获得这个bar.name……之类的,但这是行不通的。 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 顺便说一句,我正在使用Java 8和Spring启动-如果有帮助

Best regards, 最好的祝福,

Chris 克里斯

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: 以下代码将在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;
    }

So, your log statement could just use one of these variables if you put it after this snippet. 因此,如果将您的日志语句放在此代码段之后,则只能使用这些变量之一。

Something like this: 像这样:

String pack = getClass().getPackage().getName();
String[] split = pack.split("\\.");
pack = split[split.length-1];

thanks to Ernest for his tip, it works flawlessly. 多亏了欧内斯特(Ernest)的提示,它才能完美地工作。 For all others that may have the same requirement, I'll post my code below: 对于所有可能有相同要求的其他代码,我将在下面发布我的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM