Adding Generics to Custom Callbacks in Android

Adding Generics to Custom Callbacks in Android

In Android development, callbacks are frequently used to handle asynchronous operations or event listeners. Custom callbacks provide flexibility for different scenarios, and adding generics makes them more versatile while reducing the need for type casting.

Benefits of Using Generics

Generics allow you to specify the exact type when defining a callback. This avoids type casting inside the callback, enhancing code readability and type safety. Additionally, generic callbacks can be reused across different contexts, eliminating duplicate code.

Example of a Generic Custom Callback

Suppose we have an interface Callback with a method onResult. We can modify it to use generics sothat consumers can specify the concrete type.

public interface Callback<T> {
    void onResult(T result);
}

Here, the onResult method parameter is changed to the generic type T. Implementations can then specify the actual type for T.

Next, we create a User class and a method loadData that uses this generic callback.

public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void loadData(Callback<User> callback) {
        // Simulate data loading
        callback.onResult(new User("Alice", 25));
    }
}

In loadData, we use Callback<User> as the parameter type, allowing direct passing of User data in the callback.

Finally, let's demonstrate usage. In MainActivity, we create a User object and call loadData with an anonymous class implementing Callback<User>.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        User user = new User("", 0);
        user.loadData(new Callback<User>() {
            @Override
            public void onResult(User result) {
                Log.d("MainActivity", "name: " + result.getName() + ", age: " + result.getAge());
            }
        });
    }
}

With this approach, the onResult method receives a User object directly, avoiding any type casting.

Sequence Diagram

The following sequence diagram illustrates the flow described above:

(Placeholder for sequence diagram image)

State Diagram

The state diagram below shows the states of the Callback interface:

(Placeholder for state diagram image)

In this diagram, Callback has two states: Active and Inactive. Calling onResult transitions from Inactive to Active, and after the callback ends, it returns to Inactive.

By using generics in custom callbacks, you can improve code reusability and readability. This article should help you understand and apply generic custom callbacks in Android.

Tags: Android java generics callback Custom Callback

Posted on Sun, 28 Jun 2026 16:30:06 +0000 by brickstermike