rspec/rules/S2390/java/rule.adoc

44 lines
1.3 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
When a parent class references a member of a subclass during its own initialization, the results might not be what you expect because the child class might not have been initialized yet. This could create what is known as an "initialisation cycle", or even a deadlock in some extreme cases.
To make things worse, these issues are very hard to diagnose so it is highly recommended you avoid creating this kind of dependencies.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
class Parent {
static int field1 = Child.method(); // Noncompliant
static int field2 = 42;
public static void main(String[] args) {
System.out.println(Parent.field1); // will display "0" instead of "42"
}
}
class Child extends Parent {
static int method() {
return Parent.field2;
}
}
----
== Resources
2021-04-28 16:49:39 +02:00
* https://www.securecoding.cert.org/confluence/display/java/DCL00-J.+Prevent+class+initialization+cycles[CERT, DCL00-J.] - Prevent class initialization cycles
* Java Language Specifications - https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4[Section 12.4: Initialization of Classes and Interfaces]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]