【发布时间】: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)? -
我需要那个方法,为了简单起见,我没有在这里调用它。