Will calling an enum with an object reference as a value create an object every time it's called?

Rigo Sarmiento :

This became my concern mainly because of this:

public enum Method {
    POST(new Host().getAssets()),
    GET("GET"),
    DELETE("DELETE"),
    PUT("PUT");

    private String method;

    Method(String s) {
        method = s;
    }

    private String getMethod() {
        return method;
    }
}

The Host class is Spring @ConfigurationProperties annotated to be injected with values from an application.properties file at runtime. If I write that as a value of an enum, will it create a new object instance of Host every time I use Method.POST?

Shubhendu Pramanik :

No, It will create instance only once. This can be checked with a print statement like below. Here getAssets() and constructor has been called only once:

    public class Host {

    public static void main(String[] args) {
        System.out.println("Hello World!");
        System.out.println(Method.POST);
        System.out.println(Method.POST);
        System.out.println(Method.POST);
    }

    Host()
    {
        System.out.println("--------------");
    }

    String getAssets()
    {
        System.out.println("ssssssssssss");
        return "eeee";
    }
}


enum Method {
    POST(new Host().getAssets()),
    GET("GET"),
    DELETE("DELETE"),
    PUT("PUT");

    private String method;

    Method(String s) {
        method = s;
    }

    private String getMethod() {
        return method;
    }
}

O/P:

    Hello World!
--------------
ssssssssssss
POST
POST
POST

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79448&siteId=1