简体   繁体   中英

How to pass a String variable to a new object in java

I am new to Java and and not sure how to do this correctly.

I have a String variable textMain and I would like to pass it into a new object TextToSpeech . Is it possible? If so, how to do it?

I have to declare this variable outside of the object, unfortunately this object does not 'see' this variable.

String textMain = "text text";
textToSpeechSystem = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            speak(textMain); // textMain doesn't visible
        }
    }
});

Sorry if I wrote something wrong, I don't know the correct nomenclature yet.

Your object you want to pass the string needs to have a field to store the value

Let's say that you have a class TextToSpeech with a constructor that has a string parameter to set the value at object creation.

public class TextToSpeech {
  private String textMain;
  ...

  public TextToSpeech(String text, ...) {
    textMain = text;
    ...
  }
}

Or you can have a setter method in order to set the value after object creation

public void setText(String text) {
  textMain = text;
}

Any time you are referencing a local variable in an anonymous class / lambda you need to declare that variable as final (immutable).

final String textMain = "text text";
textToSpeechSystem = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            speak(textMain); // textMain doesn't visible
        }
    }
});

Thats because TextToSpeech.OnInitListener and textMain has different location in memory: TextToSpeech.OnInitListener is been located in the heap and available after current context will be closed, but textMain is been located in the stack and not available after current context will be closed.

To fix it. all you have to do is to move textMain to the heap .

final String textMain = "text text";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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