Reputation: 8747
I am C/C++
programmer and new to java. I have the following code(a part of XML RPC server/client application) and when complied with -Xlint
option I get a warning.
Code:
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://localhost:8081"));
config.setEnabledForExceptions(true);
config.setEnabledForExtensions(true);
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
Object[] params = new Object[0];
//execute returns java.lang.Object . getProcInfo has return type ArrayList<ProcInfo>
ArrayList<ProcInfo> list = (ArrayList<ProcInfo>)client.execute(config,"test.getProcInfo", params);
Warning:
warning: [unchecked] unchecked cast
What I do not understand is why there is a warning in the first place. Why there arises a need to check it when I am casting it to the same object I am returning from other function and let us say that even if there is a need then can this checking not done by the compiler itself.
How can I fix this warning.
Upvotes: 2
Views: 408
Reputation: 3417
The unchecked cast warning means that due to Java's type erasure (generic type parameters do not exist at runtime and therefore cannot be checked when casting) even if the cast succeeds, one does not know whether the type actually matches the declared generic type.
To eliminate this circumstance, instead of casting to ArrayList<ProcInfo>
cast to:
List<?> list = (List<?>)client.execute(config,"test.getProcInfo", params);
This denotes the type "Some list implementation with some element type". Then, when accessing elements of the list, cast them to ProcInfo
:
for(Object element : list){
final ProcInfo info = (ProcInfo) element;
// do something with info
}
Neither cast will then cause a warning.
Upvotes: 3
Reputation: 66657
Unchecked cast warning means, you are trying to cast from raw type to generic type.
Your execute
method returning Object, but you are casting to ArrayList<ProcInfo>
which is of generic type, so compiler warning you that return type of execute is not what you are expecting.
Two ways you can overcome this warning (I know of):
1) Add @SuppressWarnings
annotation
2) Remove generictype from ArrayList.
These methods will eliminate the compiler error.
Upvotes: 3
Reputation: 425208
The execute()
method return type is Object
, but you are casting it to the more specific type ArrayList<ProcInfo>
. The compiler is warning you that there is no guarantee bass on the method signature that it will in fact be an object of the type to are casting to.
If you are confident that the implementation will return the type you're expecting, you can tell the compiler to not issue a warning by adding this annotation to the method in which the cast is being made:
@SuppressWarnings("unchecked")
Upvotes: 0
Reputation: 44210
If you just want to ignore the warning and are sure it's safe, write @SuppressWarnings("unchecked") above the line giving you the error.
Upvotes: 1