001/** 002 * The MIT License (MIT) 003 * 004 * Copyright (c) 2018 nobark (tools4j), Marco Terzer, Anton Anufriev 005 * 006 * Permission is hereby granted, free of charge, to any person obtaining a copy 007 * of this software and associated documentation files (the "Software"), to deal 008 * in the Software without restriction, including without limitation the rights 009 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 010 * copies of the Software, and to permit persons to whom the Software is 011 * furnished to do so, subject to the following conditions: 012 * 013 * The above copyright notice and this permission notice shall be included in all 014 * copies or substantial portions of the Software. 015 * 016 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 017 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 018 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 019 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 020 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 021 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 022 * SOFTWARE. 023 */ 024package org.tools4j.nobark.queue; 025 026import java.util.Map; 027import java.util.Queue; 028import java.util.function.Supplier; 029 030/** 031 * Helper class dealing with unsafe casts necessary for factories of objects whose generic types are not known to the 032 * factory provider. 033 */ 034final class Factories { 035 036 /** 037 * Encapsulates the unsafe cast necessary when creating a queue with a factory that is unaware of the value type of 038 * the queue. 039 * 040 * @param factory the queue factory 041 * @param <V> the queue value type 042 * @return a typed queue 043 */ 044 static <V> Queue<V> createQueue(final Supplier<? extends Queue<Object>> factory) { 045 //NOTE: casting a queue that takes objects to a specific typed queue is fine as long as we only add those typed 046 // values to the queue 047 @SuppressWarnings({"unchecked"}) 048 final Queue<V> typed = (Queue<V>)factory.get(); 049 return typed; 050 } 051 052 /** 053 * Encapsulates the unsafe cast necessary when creating a map with a factory that is unaware of the key/value types 054 * of the map. 055 * 056 * @param factory the map factory 057 * @param <K> the map key type 058 * @param <V> the map value type 059 * @return a typed map 060 */ 061 static <K,V> Map<K,V> createMap(final Supplier<? extends Map<Object,Object>> factory) { 062 //NOTE: casting a map that takes object keys/values to a specific typed map is fine as long as we only put those 063 // typed keys and values to the map 064 @SuppressWarnings({"unchecked"}) 065 final Map<K,V> typed = (Map<K,V>)factory.get(); 066 return typed; 067 } 068 069 private Factories() { 070 throw new RuntimeException("No Factories for you!"); 071 } 072}