0

我想在java中的几个类之间共享一个字符串,但是字符串不是常量,所以通常的方法public static final不起作用。

我的意思是,我更新了字符串的值,这因使用而异。

目前我使用的代码是:

public String NewDestination;

 destination = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/Uploaded/"; // main location for uploads (CHANGE THIS WHEN USING PREDATOR)
            File theFile = new File(destination + "/" + username);
            theFile.mkdirs();// will create a sub folder for each user (currently does not work, below hopefully is a solution) (DOES NOW WORK)
            System.out.println("Completed Creation of folder");
            NewDestination = destination + username + "/";

上面,它是通过将目标 + 用户名 + "/" 相加创建的,因此它不能是静态最终的,因为每次登录都会更改,但我仍然需要将值传递给另一个类,我该怎么做?

编辑:

我现在所做的是:

添加public static String NewDestination;到我的 FileUploadController.java

在我的 Mybean.java 中,我添加了System.out.println(FileUploadController.NewDestination);它,它仍然打印出 null :(

4

3 回答 3

4

听起来你想要一个public staticfinal字段。

但是,这将允许其他类也更改它。
最好是创建一个private static字段,以及一个public static getDestination()允许其他类读取它的方法。

于 2013-02-04T15:19:53.047 回答
0

请注意,您不能更改String. 字符串是不可变的。您正在传递对 a的引用String,它是会改变的引用,而不是底层的String.

如果每个类都需要一个正在变化的引用String,为什么不简单地String根据需要在方法中生成并让每个类调用:

originatingObject.getDestinationPath();

这在线程环境中更容易处理(当然比使用对使用static做出一些假设的实例更容易)

于 2013-02-04T15:20:26.110 回答
0

Java 中的字符串数据类型是不可变的。在您的情况下,由于存储在变量“destination”中的值发生了变化,我建议使用 StringBuilder (这是 String 的可变伴生类)。

于 2013-02-04T15:33:32.017 回答