简体   繁体   中英

PropertyChangeListener and polymorphism inconsistencies (with packages)

When the following classes are separated into different packages it null-pointers: java.lang.NullPointerException: Cannot invoke method addPropertyChangeListener() on null object. Combining them into a single package, however, works.

Package 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 {}

Package 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"
  }
}

Put them all together into one package/file (commenting out import parents.* ) and you'll find it works, printing:

> 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]

Why is that?

将通用<Parent>添加到Parent类声明使事情再次运行:

public class Parent extends GrandParent <Parent> { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM