【发布时间】:2016-05-21 01:29:09
【问题描述】:
我知道在 java 中您可以编写一个外部类,该类可以导入到脚本中然后运行,从而允许该类在多个不同的地方使用。
我想知道是否有办法用方法做同样的事情。我发现有时我需要创建一个外部类来做一些非常小的和基本的事情,如下所示。
simpleScript.java
public class simpleScript {
public static void main() {
// just a date variable which I will want to format
// but I will always one of two formats every time
// I use a date so I need a library/class function
Date dateNow = new Date();
// to use my library/class function I have to
// initialize it first
dateFormat localDateFormat = new dateFormat();
// now I can use it in the main only
String dmyNow = localDateFormat.dmyFormat(dateNow);
String timeNow = localDateFormat.timeFormat(dateNow);
}
}
dateFormat.java
public class dateFormat() {
public static String dmyFormat(Date dateArg) {
SimpleDateFormat dmyStyle = new SimpleDateFormat("dd-MM-yyyy");
String dateResult = dmyStyle.format(dateArg);
return dateResult;
}
public static String timeFormat(Date dateArg) {
SimpleDateFormat timeStyle = new SimpleDateFormat("hh:mm:ss");
String timeResult = timeStyle.format(dateArg);
return timeResult;
}
}
这并没有让我很困扰,直到我需要在多种不同的方法中使用它,有时只在一个日期使用,所以我必须继续初始化类以使用其中的方法(我不想让它是一个全局类)。
是否有另一种方法可以使我的方法在没有类的情况下可重用(跨多个 java 文件)?
【问题讨论】:
-
您无需创建类的实例即可调用
static方法。看看这个 - stackoverflow.com/questions/942326/…