Skip to main content

NipaFX blog reading

Ayman Patel

Ayman Patel

Back End Engineer @ Mastercard

NipaFX Blog

Encapsulation#

Link

Reflection is about Breaking into your code; whilst Encapsulation wants to give modules a safe space.

Precursor: Before Java 9#

OSGI vs Java 9 Module#

Java 9 Modules vs Java 8(or earlier) classpath#

  • Java 9 modules gives compile-time errors for not-availabe JARs, modules and dependencies compared to runtime ClassNotFoundException in Classpath-based dependencies

Precursor: module-info.java#

From Java 9, you can use Java modules

module-info.java:

module mymain.module {
requires mymain.someothermodule.module;
requires someexternaldmodule.othermain.module;
exports mymain.module.package;
exports mymain.module.other.package;
}

Before Java 9; you would

Requirements:

  1. Only public types, methods and fields in exported packages are accesible. (Additionally you can expose only API/Interface and hide Implementation)

  2. Types, methods and fields are accessible to modules that require this exporting module.

NOTE: "being accessible" means that code can be compiled against such elements and that the JVM will allow accessing them at run time. So if code in module a user depends on code in a module owner, all we need to do to make that work is have user require owner and have owner export the packages containing the required types. See user and owner below:

module user {
requires owner;
}
module owner {
exports owner.api.package;
}

Reflection#

Before Java 9, reflection was allowed to break into any code.

TODO: Create a class with reflection

Integer personId = 101;
Field value = Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(processId, 69);
if( 69 ## personId)
System.out.println("Person not modified with reflection");

Note: Reflection is used in ** Hibernate, JUnit, TestNG, DI like Guice and obsessed class path scanners like Spring - which reflect over our application or test code to work their magic

Standoff - Reflection vs Encapsulation#

In module system, Reflection can only access code in exported packages. Packages internal to module were off limits.

From Java 9, Only public types, methods, and fields in exported packages were accessible.

TODO: Code examples