【问题标题】:How to use functions of an object which is accessed as a parameter to a function of another class?如何使用作为另一个类函数的参数访问的对象的函数?
【发布时间】:2019-04-11 05:10:31
【问题描述】:

这就是我想要达到的目标:

public class cls1{
  public cls1(){}                        //constructor for the sending class
  String name = "foo";                   //String I wish to access
  public String sentName(){              //Method to access the string outside
    return name;
  }
}

public class cls2{                       //Class where I wish to access the name
  public String gotName(Object obj){     //Method where I wish to call the cls1 instance
    String recvName;                     
    if(obj.getClass()==cls1.class){
      recvName = obj.sentName();         //THE PROBLEM
    }
    return recvName;
  }
}

我知道obj 直到运行时才具有 cls1 的方法和变量,因此不允许该行编译。有没有办法做到这一点?

附:我还尝试在cls2 中创建cls1 的实例:

cls1 cls1Inst;
obj=cls1Inst;
cls1Inst.sentName();

但这给出了一个空指针异常,可能是因为我试图访问 cls1 的方法而没有实际创建它的实例(我对空指针不是很清楚,请原谅我的愚蠢)。

任何帮助将不胜感激。

【问题讨论】:

  • 你在哪里打电话cls2.gotname(obj)
  • 我需要那个方法,为了简单起见,我没有在这里调用它。

标签: java object methods


【解决方案1】:

Object 是每个对象的基类。首先你必须在cls1 中进行类型转换,然后cls1 方法将可用。

改变

recvName = obj.sentName(); 

recvName = ((cls1)obj).sentName();

在这段代码中

cls1 cls1Inst;  // here it is uninitilized (null)
obj=cls1Inst;    //<------ after this statement cls1Inst will be same and null
cls1Inst.sentName();// thats why it throws null pointer exception

此代码将起作用

cls1 cls1Inst;  // here it is uninitilized (null)
cls1Inst = (cls1)obj;    // if obj is not null then typecast it. Now it is assigned to cls1Inst
cls1Inst.sentName(); // it will work perfect file

更新

或者您可以将函数参数类型从Object 更改为cls1。这可以避免检查类类型的额外检查。请参阅下面的代码。

public String gotName(cls1 obj){                     
      return obj.sentName();// No need to check class type. just return name
  } 

【讨论】:

  • 成功了,非常感谢。如果可以,如何使用第二种方法或完全偏离轨道的方法获得相同的响应?
  • @ElysianStorm 第二种方法是什么意思? bdw 查看更新的答案。如果您还有任何困惑,请问我。
  • 你的更新就是我所说的,谢谢伙计!
  • 实际上,接收方法中最好有正确的类型!如果这不可能,您最好检查类型,因为它在另一个答案中完成!
  • @jokster 是的,这将是一个很好的方法。查看更新的答案:) 谢谢
【解决方案2】:

您不能在对象类对象上调用 sentName()。您需要先将其类型转换为 cls1 类。

public class cls2{                       //Class where I wish to access the name
  public String gotName(Object obj){     //Method where I wish to call the cls1 instance
    String recvName;                     
    if(obj.getClass()==cls1.class){
      cls1 cls1Obj = (cla1)obj;
      recvName = cls1Obj.sentName();         //THE PROBLEM
    }
    return recvName;
  }
}

【讨论】:

  • 在这种情况下,instanceof 也可以工作,并且可能比直接比较类提供更好的结果。
  • @jokster,同意你的看法。
猜你喜欢
  • 2013-03-20
  • 2016-01-04
  • 2018-11-13
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
相关资源
最近更新 更多