【问题标题】:How to store the local variables data to global variables in the same class and use it如何将局部变量数据存储到同一个类的全局变量中并使用
【发布时间】:2015-08-31 16:03:26
【问题描述】:

我面临一个问题,即我需要使用来自同一类中的方法的更新字符串数据。我应该创建一个全局变量吗?如果是这样,我如何将更新的字符串数据放置到全局变量中?下面是我的代码,其中添加了注释以说明更多细节。

public class GenerateSummonPDF
{


public void userdata(String p1, String p2, String p3, String p4)
{
    String value1= p1;
    String value2= p2;
    String value3= p3;
    String value4= p4; // all the data here are constantly updating from other class



}
public static void main(String[] args)
{

  Document document = new Document();
  try
  {
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
     document.open();
     document.add(new Paragraph("")); //i need to print all the data here from the userdata
     document.close();
     writer.close();
  } catch (DocumentException e)
  {
     e.printStackTrace();
  } catch (FileNotFoundException e)
  {
     e.printStackTrace();
  }
 }

有什么解决办法吗?提前感谢您的帮助。

【问题讨论】:

  • 两种方法:1)单例对象; 2) 静态成员

标签: java eclipse string variables global


【解决方案1】:

private String value 使用get/set 方法。 休息一下,您无需更改任何内容。

您可以在这里阅读更多内容:How do getters and setters work?

在这里引用一个答案:

private String myField; //"private" means access to this is restricted

public String getMyField()
{
     //include validation, logic, logging or whatever you like here
    return this.myField;
}
public void setMyField(String value)
{
     //include more logic
     this.myField = value;
}

【讨论】:

  • 你到底是什么意思?因为我得到的只是一个“null”,也许我的代码有问题
  • 所以如果有多个值,那就意味着我需要更多的“public String getMyField()”?对吗?
  • 如果您同时更新/覆盖所有这些,您可以在一组 getter 和 setter 方法中执行此操作。如果您分别以不同方式覆盖它们,那么您应该为这些字段分别设置一组 getter 和 setter。
  • 但是“返回 this.myField;”不过只能用一个方法编写。
  • 例如:您将拥有“return this.value1;” “返回 this.value2;”等等。所有这些返回值都将在它们各自的“getvalue1()”、“getvalue2()”等方法中。
猜你喜欢
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 2021-10-12
  • 2021-02-18
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多