69 lines
1.5 KiB
Plaintext
69 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
include::../description.adoc[]
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
public class S1944 {
|
|
|
|
public static void main(String[] args) {
|
|
List<String> list = (List<String>) getAttributes(); // Noncompliant; List<Integer> return by getAttributes() is not be casted to List<String>
|
|
String s = list.get(0); // java.lang.ClassCastException will be raised here
|
|
}
|
|
|
|
private static List<?> getAttributes() {
|
|
List<Integer> result = new ArrayList<>();
|
|
result.add(0);
|
|
return result;
|
|
}
|
|
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
public class S1944 {
|
|
|
|
public static void main(String[] args) {
|
|
List<Integer> list = (List<Integer>) getAttributes(); // Compliant
|
|
String s = String.valueOf(list.get(0));
|
|
}
|
|
|
|
private static List<?> getAttributes() {
|
|
List<Integer> result = new ArrayList<>();
|
|
result.add(0);
|
|
return result;
|
|
}
|
|
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://wiki.sei.cmu.edu/confluence/x/u9UxBQ[CERT, EXP36-C.] - Do not cast pointers into more strictly aligned pointer types
|
|
* CWE - https://cwe.mitre.org/data/definitions/588[CWE-588 - Attempt to Access Child of a Non-structure Pointer]
|
|
* CWE - https://cwe.mitre.org/data/definitions/704[CWE-704 - Incorrect Type Conversion or Cast]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
"[xType]" cannot be cast to "[yType]" without a risk of "ClassCastException".
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|