简体   繁体   中英

Can I make a method which takes an instance and returns map object as static?

apologizes if I ask a dumb question. I have a method which takes an object, converts it into a map and returns the map object. It does not access any instance variable of the class in which it is declared.

logger is again a static field.

public Map<String, Object> createDocumentMap(final DocId docId) {

        logger.debug("Creating document map...");
        Map<String, Object> documentMap = new HashMap<String, Object>();
        documentMap.put("docNumber", docId.getDocNo());
        documentMap.put("docRev", docId.getDocRev());

        logger.debug("Document map ready. " + documentMap);

        return documentMap;
    }

I don't know whether to declare it as static or not despite reading many thread about static method vs non-static method.

It depends on how will you use this method. If you use it only within an instance it should stay instance method. Since this method doesn't depend on any instance variable you can change it to static. Do it in case if you will use this method from another objects. In this case you can also consider moving this method to some utility class.

If it does not depend on any instance variables (fields) or methods then you can. Otherwise you can't.

In practice static methods are often used in general purpose utility classes which does not depend on context only parameters.

正如您所提到的,您的方法是使用实​​例变量,因此您无法使用实例变量/对象创建静态方法。

Declare the map in the class as a static property.

public static Map<String, Object> documentMap = null;

and initialize it in your method.

documentMap = new HashMap<String, Object>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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