<分区>
我搜索了 stackoverflow 以及其他一些网站,遗憾的是没有找到这个问题,更不用说回答了。也许我的方法最好以另一种方式尝试?我是 Java 新手;我认为这应该是一个非常简单的答案。
问题: 我有一个static 方法,我想从中返回值。为了方便和整洁,我想使用我自己的类而不是 ArrayList、String[] 或类似的类。问题是我无法在静态方法中实例化我的类(正如我预期的那样可能是一个问题)。有趣的是:使用 String[] 或 Object 作为返回值确实有效(这是这些类的一个实例)...所以为什么我不能使用自己的类实例?
示例:
public static String[] decodeText(String codeString) {
//Parse codestring and return values (not included in this example)
String[] data = new String[3];
data[0]="This";
data[1]="does";
data[2]="work";
return data;
}
上面的效果很好,但是当我使用自己的类返回值时,编译器会给我“无法从静态上下文中引用非静态变量 this”(注意:已编辑以表明这些类嵌套在 JInputs 类中,这显然是重现错误所必需的):
public class JInputs extends JOptionPane {
//A lot of missing code here (which shouldn't be necessary to reproduce issue)
public class UserData {
public String userName;
public String code;
public long milliTime;
UserData() {
}
UserData(String userName, String code, long milliTime) {
this.userName = userName;
this.milliTime = milliTime;
this.code = code;
}
}
public static UserData decodeText(String codeString) {
//Parse codestring and return values (not included in this example)
UserData data = new UserData();
data.milliTime = System.currentTimeMillis();
data.code = "blah";
data.userName = "Me";
return data;
}
}
显然,我可以将我的 UserData 类设为静态类,但随后对该方法的调用不会更改原始调用的值吗? Java 程序员如何从静态方法返回整洁的数据?为什么它允许实例化内置类而不是用户定义类?