我试图在类之间传递一些信息,如成功或失败,失败原因,缺少数据等。 但我不确定哪种方法是正确的。此外,我无法将信息作为参数传递,因为我需要将其检索回来。由于已有返回值,因此无法返回任何值。 例如:假设我有这样的类(它只是虚拟代码实际代码非常长)
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 :(得分: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;
}
}
答案 1 :(得分: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");
}
}