I have just started using interfaces to implement listeners for asynchronous calls. Here is an example that executes a method when a database operation is complete.
//Interface
public interface DbOperationsListener {
void dbOperationCompleted(Object value, int flag);
}
//Class that calls the listener
public class UserDbOps extends DbOps {
private final UserDao dao;
public UserDbOps(Activity activity, String databaseName, boolean singleUse) {
super(activity, databaseName, singleUse);
// in super class: this.listener = (DbOperationsListener) activity
this.dao = database.userDao();
}
public void create(User user, int flag) {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> {
listener.dbOperationCompleted(dao.create(user), flag);
if (singleUse) database.close();
});
service.shutdown();
}
}
//an example where it is used
public void dbOperationCompleted(Object value, int flag) {
if (flag == RETRIEVE_USER) {
user = (User) value;
//use retrieved user
}
}
As you can see I'm casting the resulting User from an object. Is there a way to provide the type of parameter to the interface, assuming I will use it for different types (other than User
)? So that I can avoid casting the Object value
to User
or any other required type.