emoleumassi
emoleumassi

Reputation: 5139

Anonymous class how to pass local parameter?

I create a StreamResource in Vaadin. How can i pass the parameter fileName into the anonymous class? I have to set the fileName in the inner class.

Here's the source code:

String fileName;

public void anotherMethod(){
    StreamResource myResource = createResource();
    fileDownloader = new FileDownloader(myResource);
}

private StreamResource createResource() {
    return new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
            ....
            //some magic with the filename here
        }
    }, fileName);
}        

I get a NullPointerException by fileName.

Upvotes: 0

Views: 168

Answers (1)

user6367252
user6367252

Reputation:

In your code, the variable fileName is not initialized or you didn't provide this piece of code. Try initializing it like:

String fileName = "some file name"; like:

String fileName = "virus.bat";

public void anotherMethod(){
       StreamResource myResource = createResource();
        fileDownloader = new FileDownloader(myResource);
}
private StreamResource createResource() {
    final String URL = "someURL";

    return new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
              // USE THE URL.
        }
    }, fileName);
}

You don't pass the parameter to the anonymous class but to the StreamResource constructor which has two parameters: a StreamSource and a String.

I'm 100% sure you didn't assign anything to the fileName and the anonymous class has nothing to do with it! :)

Next time provide more code, at least with all the use-cases of presented variables so it'll be easier to help.

Upvotes: 1

Related Questions