美文网首页
第 33 条:优先考虑类型安全的异构容器

第 33 条:优先考虑类型安全的异构容器

作者: 综合楼 | 来源:发表于2021-05-13 21:48 被阅读0次
    优先考虑类型安全的异构容器.jpeg
    // Typesafe heterogeneous container pattern - implementation
    public class Favorites {
        private Map<Class<?>, Object> favorites = new HashMap<>();
    
        public <T> void putFavorite(Class<T> type, T instance) {
            favorites.put(Objects.requireNonNull(type), instance);
        }
    
        public <T> T getFavorite(Class<T> type) {
            return type.cast(favorites.get(type));
        }
        // Typesafe heterogeneous container pattern - client
    
        public static void main(String[] args) {
    
            Favorites f = new Favorites();
    
            f.putFavorite(String.class, "Java");
    
            f.putFavorite(Integer.class, 0xcafebabe);
    
            f.putFavorite(Class.class, Favorites.class);
    
            String favoriteString = f.getFavorite(String.class);
    
            int favoriteInteger = f.getFavorite(Integer.class);
    
            Class<?> favoriteClass = f.getFavorite(Class.class);
    
            System.out.printf("%s %x %s%n", favoriteString, favoriteInteger, favoriteClass.getName());
        }
    }
    
    // Achieving runtime type safety with a dynamic cast
    public <T> void putFavorite(Class<T> type, T instance) {
        favorites.put(type, type.cast(instance));
    }
    
    // Use of asSubclass to safely cast to a bounded type token
    static Annotation getAnnotation(AnnotatedElement element,
                                    String annotationTypeName) {
        Class<?> annotationType = null; // Unbounded type token
        try {
            annotationType = Class.forName(annotationTypeName);
        } catch (Exception ex) {
            throw new IllegalArgumentException(ex);
        }
        return element.getAnnotation(
            annotationType.asSubclass(Annotation.class));
    }
    

    相关文章

      网友评论

          本文标题:第 33 条:优先考虑类型安全的异构容器

          本文链接:https://www.haomeiwen.com/subject/wjsydltx.html