【问题标题】:How to use same object between diffrent methods如何在不同方法之间使用相同的对象
【发布时间】:2014-07-12 11:50:19
【问题描述】:

我是 Java 编码的新手。

我想知道如何在不同的方法之间传递同一个对象?

 Ex:
 Class A
 {
  //Declaring an object say
  Object obj;

  public void Method1()
  {
    //Here i want to use some method of obj
    obj=new Object();
    obj.Metod1();
  }

  public void Method2()
  {
    //Here i want to use another method of obj
    obj.Metod2();
  }
}
class B
{
 A aObj=new A();
 aObj.Method1();
 aObj.Method2();
}

从上面的代码中,我如何使用Method1()中创建的对象可以在Method2中使用?

这是我的实际代码:

public class UtilityFunctions 
{
    File fileName;
    public static FileWriter fwObj;
    public static BufferedWriter bwObj;
    Logger App_log;

    UtilityFunctions()
    {
        fileName=new File(System.getProperty("user.dir")+"\\src\\TempFile.html");
        Logger App_log=Logger.getLogger(UtilityFunctions.class);
        try
        {
            if(!fileName.exists())
                fileName.createNewFile();
            this.fwObj=new FileWriter(fileName);
            this.bwObj=new BufferedWriter(fwObj);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void writeHeader()
    {
        try
        {
            this.bwObj.append("<html><body><table border='1' style='widht:300px'><tbody><tr><th>Date</th><th>Position</th><th>Site</th></tr>");
            this.bwObj.flush();
//          this.bwObj.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void writeFooter()
    {
        try
        {
            this.bwObj.append("</html></body></table></tbody>");
            this.bwObj.flush();
            bwObj.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void writeReport(String strstrPositionName)
    {
        DateFormat format=new SimpleDateFormat("MM/dd/yyyy");
        Date date=new Date();
        String strCurrentDate=format.format(date);

        try
        {

            String strFormattedString="<tr><td>"+strCurrentDate+"</td><td>"+strstrPositionName+"</td><td>SomeSite</td></tr>";
            App_log.info("Printing the Line as: "+strFormattedString);
            this.bwObj.append(strFormattedString);
            this.bwObj.flush();
//          bwObj.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

I would like to call above methods like
Class TempClass
{
 public static void main(String args[] args)
 { 
   UtilityFunctions obj=new UtilityFunctions();
   obj.writeHeader();
   obj.writeReport("Message1");
   obj.writeReport("Message2");
   // I may add many write Report statements here.
   obj.writeFooter();
  }
}

我在这里看到的问题,writeHeader 工作正常,但是在执行 writeReport 时我得到 NullPointer 异常。如何克服?

java.lang.NullPointerException
    at UtilityFunctions.writeReport(UtilityFunctions.java:71)
    at TempClass.writeDetailedReport  etc.........

【问题讨论】:

  • 缺乏研究。有大量适合初学者的教程。

标签: java oop


【解决方案1】:

以下是如何将对象从一种方法传递到另一种方法

 public void method1()
      {
        Object objToBePassed=new Object();
        method2(objToBePassed);
      }

      public void method2(Object passedObject)
      {
        // your logic
      }

【讨论】:

    【解决方案2】:

    你应该在类的构造函数中创建你的对象,然后你就可以轻松地使用这个对象了。例如:

    class YourClass {
       private Object obj;
       public YourClass() { //constructor
          obj = new Object();
       }
       public void method() {
          //your logic
       }
    

    总而言之,如果您在构造函数中创建类的字段,则不必担心空指针,并且所有类方法都可以访问这些对象。如果你想在你的类之外使用私有字段,例如在其他类的方法中,你应该使用 getter 方法并在参数中传递对象:

    public void otherMethod(Object obj)
    

    【讨论】:

      【解决方案3】:

      首先将您的对象声明为您的类的字段:

      class MyClass
      {
          private Object obj;
      
          //...Rest of class goes here
      }
      

      在您的构造函数中初始化对象,以便在您要访问它时它不为空。

      public MyClass()
      {
          this.obj = new Object();
      }
      

      现在您可以根据需要通过两种方法访问它。

      public method1()
      {
          this.obj.doSomething();
      }
      public method2()
      {
          this.obj.doSomethingElse();
      }
      

      总而言之,它可能看起来像这样:

      class MyClass
      {
          private Object obj;
      
          public MyClass()
          {
              this.obj = new Object();
          }
      
          public method1()
          {
              this.obj.doSomething();
          }
      
          public method2()
          {
              this.obj.doSomethingElse();
          }
      
      }
      

      现在,如果您想将一个对象从一种方法实际传递给另一种方法,但又不希望任何其他方法可以访问它,您可以将其设为如下参数:

      public method1(Object obj)
      {
          obj.doSomething()
      }
      

      然后您可以从其他地方调用该方法,传递对象类型的特定实例。

      public method2()
      {
          Object obj1 = new Object();
          Object obj2 = new Object();
      
          this.method1(obj1); //All actions in method1 will be done to obj1
          this.method1(obj2); //All actions in method1 will be done to obj2
      }
      

      如果您想多次调用单个方法,但要让它作用于不同的输入,则传递参数特别有用。

      【讨论】:

      • 虽然我做了同样的事情,但仍然得到 NullPointerException。
      • 什么是NewSampClass?显然,您提供的堆栈跟踪与您声称使用的代码不对应。
      • 也不要切断痕迹。请展示全部内容。
      猜你喜欢
      • 2021-05-18
      • 2019-06-28
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      相关资源
      最近更新 更多