简体   繁体   English

Object 在 class 级别创建

[英]Object creation at class level

public class DoSomething { private static final Logger logger = LoggerFactory.getLogger(DoSomething.class);公共 class DoSomething { 私有 static 最终记录器 logger = LoggerFactory.getLogger(DoSomething.class);

private final AtomicBoolean Flag = new AtomicBoolean(false);

LogMessage logMessage= new LogMessage(); // Creating an object to call a method in it

public static final String ERROR_MAP = "ERROR_MAP";
public static final String errorJsonString = System.getenv("RESTART_ERROR_MAP");

I tried to create an object of LogMessage.我试图创建一个 LogMessage 的 object。 And use it inside a method of DoSomething class.并在 DoSomething class 的方法中使用它。 Is this fine or should I move that line inside the method?这很好还是我应该在方法内移动那条线?

You haven't told us much about your LogMessage class.您没有告诉我们太多关于您的 LogMessage class 的信息。 However, in general:但是,总的来说:

  • you should try to declare variables as close as possible to where they're first used.您应该尝试将变量声明为尽可能接近它们首次使用的位置。
  • you should try to instantiate class instances when you declare the class variable.当您声明 class 变量时,您应该尝试实例化 class 实例。
  • you should try to restrict the visibility of a variable to only that area of the code wehre it's used.您应该尝试将变量的可见性限制为仅使用它的代码区域。

If you're only using LogMessage inside a method... and if you're not going to re-use that instance across different method invocations... I'd suggest you declare and initialize it inside the method.如果您仅在方法中使用 LogMessage ...并且如果您不打算在不同的方法调用中重复使用该实例...我建议您在方法中声明并初始化它。

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

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