xsorifc28 xsorifc28 -4 years ago 53
Java Question

Generic interface error

Running the following code:

public static void get(FirebaseObject o, final Class<? extends FirebaseObject> cls, final
Callback<? extends FirebaseObject> callback) {
FirebaseDatabase.getInstance().getReference().child(o.getPath())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
FirebaseObject o = dataSnapshot.getValue(cls);
o.setKey(dataSnapshot.getKey());
cls.cast(o);
callback.onSuccess(cls.cast(o));
}

@Override
public void onCancelled(DatabaseError databaseError) {
callback.onError(databaseError);
}
});
}

public interface Callback<F extends FirebaseObject> {
void onSuccess(F firebaseObject);
void onError(DatabaseError error);
}


I get an error at
callback.onSuccess(cls.cast(o));
:

`onSuccess <capture ? extends FirebaseObject> in Callback cannot be applied to <capture ? extends FirebaseObject>`


Basically I'm trying to pass the
Class<? extends FirebaseObject> cls
that was given in
onSuccess()
, after setting the key.

Is there a workaround this error? Or an alternative implementation to achieve the goal?

Answer Source
final Class<? extends  FirebaseObject> cls,
final Callback<? extends FirebaseObject> callback

When you have these two parameters with separate ? extends constraints, it's possible for them to refer to two different subclasses. If you have two subclasses class A extends FirebaseObject and class B extends FirebaseObject, the parameters could be

final Class<A> cls, final Class<B> callback

If that were the case then callback.onSuccess(cls.cast(o)) wouldn't work because cls.cast(o) would return an A object and onSuccess would want a B.

If you intend these to refer to the same class, then you need to make that explicit by assigning it a name.

public static <T extends FirebaseObject> void get(
    FirebaseObject o, final Class<T> cls, final Callback<T> callback)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download