Java generics and SuppressWarnings

I have classes

abstract class A { //.... } class B extends A { //.... } class C extends A { //.... } 

Then i have

 interface Maker<T extends A> { SomeClass make(T obj); } 

for class maker

 class MakerForB implements Maker<B> { /*... */ } class MakerForC implements Maker<C> { /*... */ } 

and class Factory with one static method

 class Factory { public static SomeClass makeSomeClass(A obj) { Maker maker = null; if(obj instanceof B) maker = new MakerForB(); /* ... */ return maker.make(obj); } } 

In this case, I get a warning that Maker is a raw type when I declare Maker this way

 Maker<?> maker = null; 

I get an exception (make is not applicable for arguments A) on

 return maker.make(obj); 

What is the best way to get rid of these warnings without using

 @SuppressWarnings("unchecked") 
+4
source share
2 answers

Get rid of all the generics on Maker - you don't need it:

 interface Maker { SomeClass make(A obj); } class MakerForB implements Maker { SomeClass make(A obj); } 

Or, if you still want to use it, use unsafe listing or SuppressWarnings .

To understand why you get an error if your attempt to determine:

 Maker<? extends A> maker = null; 

Imagine a case where you (by chance) get maker = new MakerForC() and try applying it to B

+5
source

If I understand your question correctly, I think you could try replacing

 class Factory { public static SomeClass makeSomeClass(A obj) { Maker maker = null; if(obj instanceof B) maker = new MakerForB(); /* ... */ return maker.make(obj); } } 

by

 class Factory<S extends A> { public static SomeClass makeSomeClass(S obj) { Maker<S> maker = null; if(obj instanceof B) maker = new MakerForB(); /* ... */ return maker.make(obj); } } 

have not tested it, so if you get other errors, let me know.

-2
source

All Articles