Wiki Markup |
---|
Callers can trivially access and modify {{public}} {{static}} non-final fields. Neither accesses nor any modifications are automatically checked by a security manager, and newly set values cannot be validated. Classes loaded by the same or different class loaderloaders can access each others' {{public static}} members, unless appropriate protection is installed. For example, consider Java applets \[[Sun 08|AA. Java References#Sun 08]\]: |
...
However, applets loaded by different class loader instances are completely isolated and cannot access each others' public static
fields. unmigrated-wiki-markup
In the presence of multiple threads non-final {{public
static
}} fields can be modified in inconsistent ways (for example, see CON14-J. Do not let the "this" reference escape during object construction).
Wiki Markup |
---|
ways. Improper use of {{public static}} fields can also result in type safety issues. For example, untrusted code may supply an unexpected subtype when the variable is defined to be of a more general type such as {{java.lang.Object}}. \[[Gong 03|AA. Java References#Gong 03]\] |
...
Code Block | ||
---|---|---|
| ||
public static final FuncLoader m_functions;
// Initialize m_functions in a constructor
|
As a cautionary note, however, simply changing the modifier to final
may not prevent attackers from indirectly retrieving an incorrect value from the static
final
variable before its initialization. See MSC07-J. Eliminate class initialization cycles and , OBJ01-J. Be aware that a final reference may not always refer to immutable data for more details about such problems. Fields declared static final
are also safe for multithreaded use (CON26-J. Do not publish partially initialized objects).
It is also permissible to use a wrapper method to retrieve the value of m_functions
. This has encapsulation advantages as it restricts its accessibility to private
(see OBJ00-J. Declare data members as private and provide accessible wrapper methods).
Noncompliant Code Example
This noncompliant code example uses a public static
non-final serialVersionUID
field in a class designed for serialization.
Code Block | ||
---|---|---|
| ||
class DataSerializer implements Serializable { public static long serialVersionUID = 1973473122623778747L; // ... } |
Compliant Solution
This compliant solution declares the serialVersionUID
field as final
and limits its accessibility to private
.
Code Block | ||
---|---|---|
| ||
class DataSerializer implements Serializable { private static final long serialVersionUID = 1973473122623778747L; } |
Risk Assessment
Unauthorized modifications of public static
variables can result in unexpected behavior and violation of class invariants.
...