Type safety is very important

package test;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Test implements Favorite {
    private Map<Class<?>, Object> favorites = new HashMap<>();

    @Override
    public <T> void putFavorite(Class<T> type, T instance) {
        favorites.put(Objects.requireNonNull(type), type.cast(instance));
    }

    @Override
    public <T> T getFavorite(Class<T> type) {
        return type.cast(favorites.get(type));
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.putFavorite(String.class, "java");
        test.putFavorite(Integer.class, 1111);

        String favorite = test.getFavorite(String.class);
    }
}

To always consider the type of security, compile and run time.

 

In conclusion, the common usage of generic API (API to set an example) limit the number of fixed parameters for each type of container. You can type parameters by placing the keys on the container rather than up around this limitation. Class object can be used as this type of heterogeneous container security keys. Class object in this way is called a type token. You may also be used to customize the key type. For example, there may be a row represents a database (container) DatabaseRow type and a generic type Column <T> as a key.

Guess you like

Origin www.cnblogs.com/CherryTab/p/11884571.html