1

How do I properly design this, so it would work:

In class Property<E>:

public void addPropertyChangedListener(OnPropertyChangedListener<E> listener) {
    listeners.add(listener);
}

In class ViewModelBase:

public void addPropertyChangedListener(String propertyName, OnPropertyChangedListener<?>   listener) {
    Property<?> property = properties.get(propertyName);
    property.addPropertyChangedListener(listener); // I get error here
}

Error I get:

The method addPropertyChangedListener(Property.OnPropertyChangedListener<capture#5-of ?>)
in the type Property<capture#5-of ?> is not applicable for the arguments
(Property.OnPropertyChangedListener<capture#6-of ?>)
6
  • Just to clarify, properties.get(PropertyName) is a Property, correct? Commented Mar 29, 2014 at 20:57
  • 1
    Generalizing Jason Cs comment: Some more code showing the involved classes may be helpful - particularly, showing where E is defined. You can't add a ...Listener<?> where a ...Listener<E> is expected, but it's hard to say more based on the current code. Commented Mar 29, 2014 at 20:58
  • Just make the method generic. Commented Mar 29, 2014 at 20:58
  • @SotiriosDelimanolis Which one? Commented Mar 29, 2014 at 21:02
  • 1
    The ViewModelBase.addPropertyChangedListener and use the type variable everywhere you are using ?. Commented Mar 29, 2014 at 21:02

1 Answer 1

1
public void <T> addPropertyChangedListener(String propertyName, OnPropertyChangedListener<T>   listener) {
    Property<T> property = (Property<T>)properties.get(propertyName);
    property.addPropertyChangedListener(listener);
}

There is no way to avoid an unchecked cast warning if Properties is a heterogeneous collection. How does it even make sense (in a type system as weak as that of Java) to statically typecheck something whose type can only be known at runtime?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.