简体   繁体   English

Java:服务器端类上的静态字符串数组

[英]Java: Static string array on server side class

I want to keep a static string array to save variables passed from the client when it calls the server, and then to be able to access them from the client with a getter. 我想保留一个静态字符串数组来保存在调用服务器时从客户端传递的变量,然后能够使用getter从客户端访问它们。

for some reason i can only get very basic type (int instead of Integer for instance) to work, everything else throws a null pointer exception. 由于某种原因,我只能得到非常基本的类型(例如int而不是Integer),其他一切都会抛出空指针异常。

here is a code snippet. 这是一段代码片段。 (using GWT) (使用GWT)

@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements AddElection
{

    //this seems to be throwing a NullPointerException:
    static String[] currentElections;
    static int index;

    public String electionServer(String input) {
        // save currently running elections 
        currentElections[index] = input;
        index = index + 1;

        // TODO: getcurrentElections

So. 所以。 my question is, if i want to temporarily store a string array at the server side and be able to access it, how would i do this in google web toolkit? 我的问题是,如果我想暂时存储服务器端的字符串数组并能够访问它,我将如何在谷歌网络工具包中这样做? thanks! 谢谢!

You havn't initialized your static array. 你没有初始化你的静态数组。

At least you have to do something like this: 至少你必须做这样的事情:

static String[] currentElections = new String[ 100 ];

But it seems that your array could grow with time, so it's better to use a collection class instead: 但似乎您的数组可能会随着时间而增长,因此最好使用集合类:

static List<String > currentElections = new ArrayList<String >();

public String electionServer(String input) {
    // save currently running elections    
    currentElections.add( input );
}

But be careful if this method can be called simultaneously from several clients. 但是如果可以从多个客户端同时调用此方法,请小心。 Then you have to synchronize access like this: 然后你必须像这样同步访问:

static List<String > currentElections = 
    Collections.synchronizedList( new ArrayList<String >() );

Your array is not initialized. 您的数组未初始化。 Btw, you should not use static variables in a multi threaded applications. 顺便说一句,你不应该在多线程应用程序中使用static变量。

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

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