简体   繁体   English

全局字符串变量的Java声明

[英]Java declaration of global string variables

I am writing a server program and a client program. 我正在编写服务器程序和客户端程序。 I named the server code file server.java. 我将服务器代码文件命名为server.java。 The client runs from a different machine. 客户端从不同的计算机运行。 One of the things the client can do is upload files to the server. 客户端可以做的一件事就是将文件上传到服务器。 I want the server to store the uploaded files in a folder which resides in the same directory as the server.java program file. 我希望服务器将上传的文件存储在与server.java程序文件位于同一目录的文件夹中。 So I used the following code: 所以我使用了以下代码:

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

This did work. 这确实有效。 However I have to declare this variable separately in all the different classes I am writing. 但是我必须在我写的所有不同类中分别声明这个变量。 I want to make this a global string variable so that I dont have to declare this every time I add a new class or method. 我想让它成为一个全局字符串变量,这样我每次添加新的类或方法时都不必声明它。

So at the beginning of the program I tried: 所以在程序开始时我尝试了:

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

This gives me an error saying Cannot make a static reference to the non-static method getClass() from the type Object . 这给了我一个错误说Cannot make a static reference to the non-static method getClass() from the type Object

How else can I get this variable to be accessible globally? 我怎样才能让这个变量在全球范围内可访问?

Use a class literal from the class you're declaring the variable in. 使用您声明变量的类中的类文字。

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

Consider making the variable final if it's a constant and won't ever change. 如果变量是常量并且永远不会改变,请考虑将变量final Additionally, the normal Java variable naming convention would say to name the variable in camel case, eg serverFilesLocation , or if it's a constant, in ALL CAPS, eg SERVER_FILES_LOCATION . 此外,正常的Java变量命名约定会说以驼峰serverFilesLocation命名变量,例如serverFilesLocation ,或者如果它是常量,则在ALL CAPS中,例如SERVER_FILES_LOCATION

delete static in your declaration of the variable. 在变量声明中删除static All the instances will be able to access one instance's copy of it if both the variable and the instance in question are public. 如果变量和实例都是公共的,那么所有实例都能够访问一个实例的副本。

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

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