当以下类被分成不同的包时,它会指向空指针:java.lang.NullPointerException: Cannot invoke method addPropertyChangeListener() on null object.
然后将它们组合到一个包中。
包裹parents
:
package parents
import groovy.beans.Bindable
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
@Bindable
class GrandParent<T extends Parent> implements PropertyChangeListener {
String pets
GrandParent() {
this.addPropertyChangeListener(this)
}
@Override
void propertyChange(PropertyChangeEvent evt) {
println "prop change -> $evt"
}
}
class Parent extends GrandParent {}
套餐children
package children
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import groovy.beans.Bindable
import parents.*
class Child extends Parent {
@Bindable
String brothers
static main(args) {
Child child = new Child()
child.pets = "Leo, Sophie"
child.brothers = "Douglas, Ted"
}
}
将它们放在一个包/文件中(注释掉import parents.*
),你会发现它有效,打印:
> prop change -> java.beans.PropertyChangeEvent[propertyName=pets; oldValue=null; newValue=Leo, Sophie; propagationId=null; source=children.Child@7eceb95b]
> prop change -> java.beans.PropertyChangeEvent[propertyName=brothers; oldValue=null; newValue=Douglas, Ted; propagationId=null; source=children.Child@7eceb95b]
为什么?
答案 0 :(得分:0)
将通用<Parent>
添加到Parent类声明使事情再次运行:
public class Parent extends GrandParent <Parent> { ... }