[英]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. 实际上,
static
方法通常用于通用实用程序类,它不依赖于仅上下文参数。
正如您所提到的,您的方法是使用实例变量,因此您无法使用实例变量/对象创建静态方法。
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>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.