[英]Java static nested classes in separate files
I'm working on my own game engine and came to a wall that stopped me.我正在开发自己的游戏引擎,但遇到了阻止我的墙。 When I'll be coding a game I will simply use my gameengine.jar as a library.
当我编写游戏时,我将简单地使用我的 gameengine.jar 作为库。 But I want to reference some classes with a god-class "GameEngine".
但我想引用一些具有神级“GameEngine”的类。
In this example I will want to use a class "Logger" that simply logs errors.在此示例中,我将要使用仅记录错误的 class “记录器”。 Both GameEngine and Logger don't have a constructor, they are static.
GameEngine 和 Logger 都没有构造函数,它们是 static。
public class GameEngine{
public static Logger logger = Logger; // ERROR
}
class Logger{
static void logError(){
System.out.println("Error");
}
}
I want to do GameEngine.logger.logError();
我想做
GameEngine.logger.logError();
but can't.但不能。
I could use a nested class but both classes are very long.我可以使用嵌套的 class 但这两个类都很长。
Solution A:解决方案 A:
public class Logger{
public static void logError(){
System.out.println("Error");
}
}
And from anywhere in the code then:然后从代码中的任何地方:
Logger.logError();
SOlution B if you want to call it from GameEngine on top:解决方案 B 如果您想从顶部的 GameEngine 调用它:
public class GameEngine{
public static Logger logger = new Logger();
}
(Meaning the constructor of Logger isn't private) (意味着 Logger 的构造函数不是私有的)
then from anywhere in the code:然后从代码中的任何地方:
GameEngine.logger.logError();
Standard logging API标准测井 API
There no reason for you to re-implement a logging API while dozen of them exist in Java.您没有理由重新实现日志记录 API,而其中有十几个存在于 Java 中。
For example there log4j that is well known: https://logging.apache.org/log4j/2.x/manual/api.html For example there log4j that is well known: https://logging.apache.org/log4j/2.x/manual/api.html
And there also a standard in java to hide the actual logger implementation and provide a common interface ( https://www.vogella.com/tutorials/Logging/article.html ) java 中还有一个标准来隐藏实际的记录器实现并提供一个通用接口( https://www.vogella.com/tutorials/Logging/article.ZFC35FDC70D5FC69A369883A822C )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.