Is my code safe?

I'm sure this is a safe type, but just wanted to check how Eclipse asks me to add the @SuppressWarnings("unchecked") annotation.

 Map<String, IFace> faces; public <T extends IFace> T getFace(String key) { return (T) faces.get(key); } 
+6
source share
3 answers

This is not a safe type. You increase the rating, so if you use an incompatible derived class, at some point you will encounter an error.

For example, if A_Face and B_Face extended by IFace . At some point you can pour B_Face as A_Face , which is not type safe.

+4
source

Look at the extreme case. IFace say IFace is an acutally Object , then your code looks like this:

 static Map<String, Object> myMap = new HashMap<>(); public static void main(String[] args) throws Exception { myMap.put("ONE", 1); myMap.put("TWO", "TWO"); myMap.put("THREE", new Date()); final Calendar calendar1 = getThing("ONE"); final Calendar calendar2 = getThing("TWO"); final Calendar calendar3 = getThing("THREE"); } public static <T> T getThing(String key) { return (T) myMap.get(key); } 

So you put in a class than extends Object in your Map (so any class ).

But, when you call getThing , you do an implicit cast to your desired type. It should be pretty obvious that I can call getThing with any class as well, and it will blindly try to apply to it.

In the above example, I put some things in my Map , and then try to get them all like Calendar s.

0
source

The classic way to handle this is with a "heterogeneous heterogeneous container":

 Map<Class<?>, IFace> faces; public <T extends IFace> T getFace(Class<T> key) { return t.cast(faces.get(key)); } 

You use the interface class as a key, not a string, and then you can use the class passed as the key to safely use the return value in the desired type.

0
source

Source: https://habr.com/ru/post/951489/


All Articles