rspec/rules/S6216/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

48 lines
1.4 KiB
Plaintext

== Why is this an issue?
In general, altering or bypassing the accessibility of classes, methods, or fields violates the encapsulation principle and could lead to runtime errors. For records the case is even trickier: you cannot change the visibility of records's fields and trying to update the existing value will lead to ``++IllegalAccessException++`` at runtime.
This rule raises an issue when reflection is used to change the visibility of a record's field, and when it is used to directly update a record's field value.
=== Noncompliant code example
[source,java]
----
record Person(String name, int age) {}
Person person = new Person("A", 26);
Field field = Person.class.getDeclaredField("name");
field.setAccessible(true); // secondary
field.set(person, "B"); // Noncompliant
----
== Resources
* https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.10[Records specification]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Primary: Remove this private field update which will never succeed
Secondary: Remove this accessibility bypass which will never succeed
=== Highlighting
Primary: call to [set|setLong|setInt|...] on a ``++Field++`` instance of record's field
Secondary: call to setAccessible(true) on a ``++Field++`` instance of record's field
endif::env-github,rspecator-view[]