假设我有三个班级Parent
,ClassA
和ClassB
。 ClassA将ClassB作为其变量之一,它是Thread
的扩展,包括:
父:
class Parent {
private HashMap<ClassA, Letter> map;
public void writeToMap(ClassA a, Letter l) {
map.put(a, l);
}
}
ClassA的:
class ClassA {
private ClassB instance;
.
.
.
}
然后我有了ClassB:
class ClassB extends Thread{
//Inner variables
public void run() {
//do some work
//At some point it receives an object through a Socket
incomingLetter = (Letter) socketIn.readObject();
//Here I need put in the Parent class' map the Letter object I just read
//as well as the instance of ClassA that holds this one instance of ClassB
}
如何从ClassA
对象中抓取实例化ClassB
对象的ClassB
实例,以便将其添加到地图中?这在编程方面是否可以在Java中使用?
答案 0 :(得分:2)
您可以修改B类,使其包含对构造函数传递的A类的引用:
Class ClassB extends Thread {
private ClassA classA;
public ClassB(ClassA classA) {
this.classA = classA;
}
...
}
如果已经创建了B类,请添加方法setClassA
...
public void setClassA(ClassA classA) {
this.classA = classA;
}