|
| 1 | +# Microsphere Java- User Guide |
| 2 | + |
| 3 | +## 🔭 Brief Overview |
| 4 | + |
| 5 | +`microsphere-java` is a **Java utility library** — a reusable toolkit that makes everyday Java programming tasks easier. Think of it like a Swiss Army knife: it doesn't do one big thing, it gives you many small, well-crafted tools. It contains **~340 Java source files** organized into focused modules and packages. |
| 6 | + |
| 7 | +--- |
| 8 | + |
| 9 | +## 📦 Module Breakdown |
| 10 | + |
| 11 | +The project is split into several Maven modules (sub-projects): |
| 12 | + |
| 13 | +| Module | What it does | |
| 14 | +|---|---| |
| 15 | +| `microsphere-java-annotations` | Custom Java annotations (labels you attach to code) | |
| 16 | +| `microsphere-java-core` | The main utility library | |
| 17 | +| `microsphere-java-test` | Test utilities | |
| 18 | +| `microsphere-annotation-processor` | Compile-time annotation processing | |
| 19 | +| `microsphere-jdk-tools` | JDK compiler tools | |
| 20 | +| `microsphere-lang-model` | Language model utilities | |
| 21 | + |
| 22 | +--- |
| 23 | + |
| 24 | +## 🧩 Step-by-Step Breakdown of Each Package |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +### 1. `io.microsphere.annotation` — Custom Annotations |
| 29 | + |
| 30 | +**What it is:** Java annotations are like sticky notes you attach to your code. These custom ones communicate intent to developers. |
| 31 | + |
| 32 | +Key annotations: |
| 33 | +- `@Since("1.0.0")` — marks when a class/method was introduced (like a changelog label) |
| 34 | +- `@Experimental` — warns "this API might change" |
| 35 | +- `@Immutable` — signals an object won't change after creation |
| 36 | +- `@Nullable` / `@Nonnull` — tells readers (and tools) whether a value can be `null` |
| 37 | + |
| 38 | +```java |
| 39 | +// Example: Mark a method as introduced in version 1.0 |
| 40 | +@Since("1.0.0") |
| 41 | +public void myMethod() { ... } |
| 42 | + |
| 43 | +// Warn a caller that null might come back |
| 44 | +@Nullable |
| 45 | +public String findUser(int id) { ... } |
| 46 | +``` |
| 47 | + |
| 48 | +--- |
| 49 | + |
| 50 | +### 2. `io.microsphere.event` — Event Publishing System |
| 51 | + |
| 52 | +**What it is:** An implementation of the **Observer pattern** — when something happens (an event), anyone who cares (a listener) gets notified automatically. |
| 53 | + |
| 54 | +Key classes: |
| 55 | +- `Event` — the base class for every event; records the timestamp automatically |
| 56 | +- `EventListener<E>` — an interface you implement to react to events; supports **priority** (lower number = higher priority) |
| 57 | +- `EventDispatcher` — the hub that registers listeners and fires events; two flavors: |
| 58 | + - `DirectEventDispatcher` — notifies listeners one-by-one in the same thread |
| 59 | + - `ParallelEventDispatcher` — notifies listeners using a thread pool (in parallel) |
| 60 | +- `AbstractEventDispatcher` — the shared logic; caches which listener handles which event type |
| 61 | + |
| 62 | +```java |
| 63 | +// 1. Define an event |
| 64 | +class UserLoggedIn extends Event { |
| 65 | + public UserLoggedIn(Object source) { super(source); } |
| 66 | +} |
| 67 | + |
| 68 | +// 2. Define a listener |
| 69 | +class WelcomeListener implements EventListener<UserLoggedIn> { |
| 70 | + public void onEvent(UserLoggedIn event) { |
| 71 | + System.out.println("Welcome! Logged in at: " + event.getTimestamp()); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +// 3. Wire them up |
| 76 | +EventDispatcher dispatcher = EventDispatcher.newDefault(); |
| 77 | +dispatcher.addEventListener(new WelcomeListener()); |
| 78 | +dispatcher.dispatch(new UserLoggedIn("myApp")); // triggers WelcomeListener |
| 79 | +``` |
| 80 | + |
| 81 | +--- |
| 82 | + |
| 83 | +### 3. `io.microsphere.lang` — Core Language Abstractions |
| 84 | + |
| 85 | +**What it is:** Small but powerful interfaces and classes that improve code design. |
| 86 | + |
| 87 | +- **`Prioritized`** — anything that needs ordering (lower integer = first). Used by event listeners, converters, etc. |
| 88 | +- **`Wrapper`** — lets one object "wrap" another and expose `unwrap(MyType.class)` to retrieve the inner object. Very common in proxy/decorator patterns (like JDBC `Connection` wrappers). |
| 89 | +- **`DelegatingWrapper`** — a default wrapper that delegates all calls to the wrapped object. |
| 90 | +- **`MutableInteger`** — a mutable `int` holder (handy in lambdas where variables must be "effectively final"). |
| 91 | + |
| 92 | +```java |
| 93 | +// Prioritized: higher-priority tasks run first |
| 94 | +class HighPriorityTask implements Prioritized { |
| 95 | + public int getPriority() { return Prioritized.MAX_PRIORITY; } // runs first |
| 96 | +} |
| 97 | +``` |
| 98 | + |
| 99 | +--- |
| 100 | + |
| 101 | +### 4. `io.microsphere.lang.function` — Throwable Functional Interfaces |
| 102 | + |
| 103 | +**What it is:** Java's standard `Function`, `Consumer`, `Supplier` etc. cannot declare checked exceptions. These classes solve that limitation. |
| 104 | + |
| 105 | +- `ThrowableFunction<T,R>` — like `Function<T,R>` but `apply()` can throw any exception |
| 106 | +- `ThrowableConsumer<T>` — like `Consumer<T>` but can throw |
| 107 | +- `ThrowableSupplier<T>` — like `Supplier<T>` but can throw |
| 108 | +- `ThrowableAction` — like `Runnable` but can throw |
| 109 | +- `Streams` / `Predicates` — stream/filter helpers |
| 110 | + |
| 111 | +```java |
| 112 | +// Parse a file path that might throw IOException |
| 113 | +ThrowableFunction<String, byte[]> reader = path -> Files.readAllBytes(Paths.get(path)); |
| 114 | + |
| 115 | +// Safe execution: wraps checked exception in RuntimeException |
| 116 | +byte[] data = reader.execute("/some/file.txt"); |
| 117 | + |
| 118 | +// Or with a fallback: |
| 119 | +byte[] data = reader.execute("/some/file.txt", (path, ex) -> new byte[0]); |
| 120 | +``` |
| 121 | + |
| 122 | +--- |
| 123 | + |
| 124 | +### 5. `io.microsphere.collection` — Collection Utilities |
| 125 | + |
| 126 | +**What it is:** Utility methods and classes on top of Java's built-in collections. |
| 127 | + |
| 128 | +Key utilities: |
| 129 | +- `CollectionUtils` — `isEmpty()`, `isNotEmpty()`, `asIterable()`, etc. |
| 130 | +- `MapUtils` / `ListUtils` / `SetUtils` — helpers for Maps, Lists, Sets |
| 131 | +- `ArrayStack` — a stack backed by an ArrayList |
| 132 | +- `SingletonIterator` / `SingletonDeque` — collections holding exactly one element |
| 133 | +- `UnmodifiableDeque` / `ReadOnlyIterator` — unmodifiable wrappers |
| 134 | +- `DelegatingIterator` / `DelegatingDeque` — decorators that forward calls to an inner object |
| 135 | + |
| 136 | +```java |
| 137 | +List<String> list = null; |
| 138 | +if (CollectionUtils.isEmpty(list)) { |
| 139 | + System.out.println("Nothing here"); // safe — no NullPointerException |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +--- |
| 144 | + |
| 145 | +### 6. `io.microsphere.convert` — Type Conversion |
| 146 | + |
| 147 | +**What it is:** A flexible strategy for converting values from one type to another (e.g., `String` → `Integer`). |
| 148 | + |
| 149 | +- `Converter<S,T>` — functional interface: given a source type `S`, produce a target type `T` |
| 150 | +- `Converters` — discovers all registered converters via Java's SPI (Service Provider Interface) |
| 151 | +- Multiple converters can coexist; `Prioritized` decides which one wins |
| 152 | + |
| 153 | +```java |
| 154 | +// Convert a String to an Integer if a converter is registered |
| 155 | +Integer value = Converter.convertIfPossible("42", Integer.class); |
| 156 | +``` |
| 157 | + |
| 158 | +--- |
| 159 | + |
| 160 | +### 7. `io.microsphere.util` — General Utilities |
| 161 | + |
| 162 | +**What it is:** A broad set of helper classes for common operations. |
| 163 | + |
| 164 | +Major utilities: |
| 165 | +- `StringUtils` — string checks, manipulations |
| 166 | +- `ClassUtils` — class loading, type checking, hierarchy traversal |
| 167 | +- `AnnotationUtils` — reading and searching annotations on classes/methods |
| 168 | +- `ArrayUtils` — array length, containment, etc. |
| 169 | +- `ExceptionUtils` / `ThrowableUtils` — wrap/unwrap exceptions cleanly |
| 170 | +- `ServiceLoaderUtils` — load SPI services with error handling |
| 171 | +- `StopWatch` — measure elapsed time for profiling |
| 172 | +- `Version` / `VersionUtils` — parse and compare `1.2.3`-style version strings |
| 173 | +- `ShutdownHookUtils` — register cleanup code that runs on JVM shutdown |
| 174 | + |
| 175 | +```java |
| 176 | +// Time how long something takes |
| 177 | +StopWatch sw = new StopWatch(); |
| 178 | +sw.start("my task"); |
| 179 | +// ... do work ... |
| 180 | +sw.stop(); |
| 181 | +System.out.println(sw.prettyPrint()); |
| 182 | + |
| 183 | +// Compare versions |
| 184 | +Version v1 = Version.of("1.2.3"); |
| 185 | +Version v2 = Version.of("1.3.0"); |
| 186 | +System.out.println(v1.compareTo(v2)); // negative: v1 < v2 |
| 187 | +``` |
| 188 | + |
| 189 | +--- |
| 190 | + |
| 191 | +### 8. `io.microsphere.reflect` — Reflection Utilities |
| 192 | + |
| 193 | +**What it is:** Java reflection lets you inspect and call classes/methods/fields at runtime. These utilities wrap the boilerplate and handle edge cases. |
| 194 | + |
| 195 | +Key classes: |
| 196 | +- `MethodUtils` / `FieldUtils` / `ConstructorUtils` — find and invoke methods/fields/constructors safely |
| 197 | +- `TypeUtils` — generic type resolution (e.g., "what is the `T` in `List<T>`?") |
| 198 | +- `ReflectionUtils` — common reflection helpers |
| 199 | +- `ProxyUtils` — work with JDK dynamic proxies |
| 200 | + |
| 201 | +```java |
| 202 | +// Find a method by name and invoke it |
| 203 | +Method m = MethodUtils.findMethod(MyClass.class, "doSomething", String.class); |
| 204 | +Object result = MethodUtils.invokeMethod(instance, m, "hello"); |
| 205 | +``` |
| 206 | + |
| 207 | +--- |
| 208 | + |
| 209 | +### 9. `io.microsphere.io` — I/O Utilities |
| 210 | + |
| 211 | +**What it is:** Helpers for reading files, scanning classpaths, and filtering resources. |
| 212 | + |
| 213 | +- `io.scanner` — scan classpath entries (JARs, directories) for classes or resources |
| 214 | +- `io.filter` — file/resource filters |
| 215 | +- `io.event` — file change events (e.g., watch a directory) |
| 216 | + |
| 217 | +--- |
| 218 | + |
| 219 | +### 10. `io.microsphere.logging` — Logging Abstraction |
| 220 | + |
| 221 | +**What it is:** A thin abstraction over whatever logging framework is on the classpath (SLF4J, JUL, etc.). |
| 222 | + |
| 223 | +```java |
| 224 | +Logger logger = LoggerFactory.getLogger(MyClass.class); |
| 225 | +logger.info("Starting up..."); |
| 226 | +``` |
| 227 | + |
| 228 | +--- |
| 229 | + |
| 230 | +### 11. `io.microsphere.concurrent` — Concurrency Utilities |
| 231 | + |
| 232 | +**What it is:** Thread-safe helpers and `ThreadLocal` tools for concurrent programs. |
| 233 | + |
| 234 | +--- |
| 235 | + |
| 236 | +### 12. `io.microsphere.net` — Network Utilities |
| 237 | + |
| 238 | +**What it is:** URL/URI building utilities, classpath URL handlers, and console URL handlers. |
| 239 | + |
| 240 | +--- |
| 241 | + |
| 242 | +### 13. `io.microsphere.json` — JSON Utilities |
| 243 | + |
| 244 | +**What it is:** Lightweight JSON parsing and creation (`JSONObject`, `JSONArray`, `JSONTokener`) — a local, dependency-free JSON library similar to `org.json`. |
| 245 | + |
| 246 | +--- |
| 247 | + |
| 248 | +### 14. `io.microsphere.metadata` — Configuration Property Metadata |
| 249 | + |
| 250 | +**What it is:** Reads and generates Spring-Boot-style `additional-spring-configuration-metadata.json` configuration property metadata, allowing IDE auto-completion for configuration keys. |
| 251 | + |
| 252 | +--- |
| 253 | + |
| 254 | +## 🔑 Key Concepts / Terminology |
| 255 | + |
| 256 | +| Term | Plain English | |
| 257 | +|---|---| |
| 258 | +| **Interface** | A contract: defines *what* methods must exist, not *how* | |
| 259 | +| **`@FunctionalInterface`** | An interface with exactly one method — can be used as a lambda | |
| 260 | +| **Generics (`<T>`)** | Placeholder for a type that gets filled in later — avoids casts | |
| 261 | +| **SPI (Service Provider Interface)** | A Java mechanism to load implementations by placing a file in `META-INF/services/` | |
| 262 | +| **Observer Pattern** | Publisher fires events; subscribers (listeners) react — they're decoupled | |
| 263 | +| **Wrapper/Decorator Pattern** | Wrap an object to add or change behavior without modifying the original | |
| 264 | +| **Reflection** | Inspect or invoke classes/methods at runtime, even if you don't know them at compile time | |
| 265 | + |
| 266 | +--- |
| 267 | + |
| 268 | +## 🚀 Common Use Cases |
| 269 | + |
| 270 | +- **Add custom annotations** to your API (use `microsphere-java-annotations`) to document stability, nullability, and version history. |
| 271 | +- **Publish/subscribe to events** within a JVM (use `EventDispatcher`) without a message broker. |
| 272 | +- **Safely call code that throws** checked exceptions inside streams or lambdas (use `ThrowableFunction`). |
| 273 | +- **Convert types** in a pluggable, prioritized way (use `Converter`). |
| 274 | +- **Traverse class hierarchies / read generics at runtime** (use `TypeUtils`, `ClassUtils`). |
| 275 | +- **Measure performance** during debugging (use `StopWatch`). |
| 276 | +- **Sort tasks/listeners by priority** (implement `Prioritized`). |
| 277 | + |
| 278 | +--- |
| 279 | + |
| 280 | +## 🧑💻 How It All Fits Together (mini end-to-end example) |
| 281 | + |
| 282 | +```java |
| 283 | +// 1. Define a typed event |
| 284 | +class OrderPlaced extends Event { |
| 285 | + private final String orderId; |
| 286 | + public OrderPlaced(Object source, String orderId) { |
| 287 | + super(source); |
| 288 | + this.orderId = orderId; |
| 289 | + } |
| 290 | + public String getOrderId() { return orderId; } |
| 291 | +} |
| 292 | + |
| 293 | +// 2. Implement a listener with HIGH priority |
| 294 | +class AuditListener implements EventListener<OrderPlaced> { |
| 295 | + public void onEvent(OrderPlaced e) { |
| 296 | + System.out.println("AUDIT: order " + e.getOrderId() + " at " + e.getTimestamp()); |
| 297 | + } |
| 298 | + public int getPriority() { return Prioritized.MAX_PRIORITY; } // runs first |
| 299 | +} |
| 300 | + |
| 301 | +// 3. Wire up and fire |
| 302 | +EventDispatcher dispatcher = EventDispatcher.newDefault(); |
| 303 | +dispatcher.addEventListener(new AuditListener()); |
| 304 | +dispatcher.dispatch(new OrderPlaced(this, "ORD-001")); |
| 305 | +// → AUDIT: order ORD-001 at 1716726766000 |
| 306 | +``` |
| 307 | + |
| 308 | +This library's design keeps individual pieces small, testable, and composable — a great pattern to study when learning professional Java development. |
0 commit comments