繁体   English   中英

全局字符串变量的Java声明

[英]Java declaration of global string variables

我正在编写服务器程序和客户端程序。 我将服务器代码文件命名为server.java。 客户端从不同的计算机运行。 客户端可以做的一件事就是将文件上传到服务器。 我希望服务器将上传的文件存储在与server.java程序文件位于同一目录的文件夹中。 所以我使用了以下代码:

String server_files_location = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

这确实有效。 但是我必须在我写的所有不同类中分别声明这个变量。 我想让它成为一个全局字符串变量,这样我每次添加新的类或方法时都不必声明它。

所以在程序开始时我尝试了:

public static String server_files_location = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 

这给了我一个错误说Cannot make a static reference to the non-static method getClass() from the type Object

我怎样才能让这个变量在全球范围内可访问?

使用您声明变量的类中的类文字。

public static String server_files_location =
    YourClass.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

如果变量是常量并且永远不会改变,请考虑将变量final 此外,正常的Java变量命名约定会说以驼峰serverFilesLocation命名变量,例如serverFilesLocation ,或者如果它是常量,则在ALL CAPS中,例如SERVER_FILES_LOCATION

在变量声明中删除static 如果变量和实例都是公共的,那么所有实例都能够访问一个实例的副本。

暂无
暂无

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

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