2015-04-24 32 views
-1

我想传递类之间的一些信息,如成功或失败,失败的原因,缺失的数据等 但我不知道哪个是正确的方式来做到这一点。此外,我无法将信息作为参数传递,因为我需要将其恢复。由于已有返回值,因此无法返回任何值。 例如:假设我有类这样的(它只是哑代码的实际代码很长)如何在对象之间传递数据

class A { 
    B b = new B(); 
    C c = new C(); 
    b.putData(); 
    c.putData(); 

    //Want to print all the inforamtion of what happend 
    //in methods of putData and getData. How to do that? 
} 

class B { 

    boolean putData() { 
     D d = new D(); 
     Data data =d.getData(); 
     //some code goes here 
    } 
} 
Class C{ 
    boolean putData() { 
     //some code here 
    } 
} 
+0

传递一个对象作为参数? – jean

+1

'想要以最简单的方式为您感兴趣的值添加System.out.println(...)'语句,打印putData和getData.'方法中发生的所有事件的信息。更好的方法:更改你的问题要清楚你想要达到什么目的。 – SubOptimal

+0

对不起,我忘记提及我无法传递参数,因为我必须将其恢复,这是我无法完成的,因为所有方法都已返回一些对象。 – ABYS

回答

0

看看下面的代码可以帮助你。

class A { 
    B b = new B(); 
    C c = new C(); 
    String resultClassB = b.putData(); 
    String resultClassC = c.putData(); 

    System.out.println(resultClassB); 
    System.out.println(resultClassC) 

    //Want to print all the inforamtion of what happend 
//in methods of putData and getData. How to do that? 
} 

class B { 

    String putData() { 
    D d = new D(); 
    String data =d.getData(); 
    //some code goes here 

    return data' 

} 

} 
Class C { 
    String putData() { 
    //some code here 
    String result = "reason for failure and success"; 
    return result' 
    } 
} 

class Data(){ 
    String getData(){ 
     String data = "get all data to print using some logic"; 
     return data; 
    } 
} 
+0

感谢E_net4的帮助。我可以使用getter方法。但是,如果你可以帮助一些小的示例代码,我仍然会很感激。 – ABYS

+0

只是抬起头来:那不是我的答案。我宁愿将数据分开放入不同的方法中。 –

0

您可以使用try {} catch(Exception){}在出现问题时获取信息。

Succes将是一个有效的返回对象。

class A { 
      B b = new B(); 
      C c = new C(); 
      b.putData(); 
      try 
      { 
       c.putData(); 
      } 
      catch(Exception e) 
      { 
       //do error handling, or print stacktrace 
      } 

      //Want to print all the inforamtion of what happend 
     //in methods of putData and getData. How to do that? 
     } 

    class B { 

     boolean putData() { 
      D d = new D(); 
      Data data =d.getData(); 
      //some code goes here 
     } 
    } 
     Class C{ 
     boolean putData() throws Exception{ 
      if(<data_missing>) throw new Exception("Data missing"); 
     } 
} 
+0

请问打印信息的目的是什么?你真的需要它在代码中,还是你想创建一个记录器? – JohannisK