### Install and Run Objenesis TCK on Android Source: https://context7.com/easymock/objenesis/llms.txt Use these ADB commands to install the Objenesis TCK APK on an Android device and then run the instrumentation tests. ```bash adb install -r objenesis-tck-android-3.5.apk ``` ```bash adb shell am instrument -w org.objenesis.tck.android/.TckInstrumentation ``` -------------------------------- ### Configure Sonatype repository settings Source: https://github.com/easymock/objenesis/blob/master/README.md Example configuration for settings.xml to deploy artifacts to the Sonatype Maven repository. ```xml ossrh sonatypeuser sonatypepassword ``` -------------------------------- ### Reproducible build commands Source: https://github.com/easymock/objenesis/blob/master/README.md Commands for checking plugin compatibility, building, installing, and comparing artifacts for reproducible builds. ```bash # Checks that all plugins are compatible mvn artifact:check-buildplan -Pfull,all # Build and install the artifact mvn clean install -Pfull,all # Build and compare the artifact with the installed one mvn clean verify artifact:compare -Pfull,all ``` -------------------------------- ### Run Android TCK build Source: https://github.com/easymock/objenesis/blob/master/README.md Compiles the project for the Android TCK. Ensure Android SDK and platform-tools are installed and ANDROID_HOME is set. ```bash mvn package -Pandroid ``` -------------------------------- ### Instantiate Object with ObjenesisStd Source: https://github.com/easymock/objenesis/blob/master/website/site/content/tutorial.html Use ObjenesisStd for standard object instantiation where no constructor is called. This is a quick way to get an instance. ```java Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer MyThingy thingy1 = (MyThingy) objenesis.newInstance(MyThingy.class); ``` -------------------------------- ### Implement Custom Instantiation Strategy Source: https://github.com/easymock/objenesis/blob/master/website/site/content/details.html Create a custom InstantiatorStrategy to optimize instantiation for a specific JVM or to support environments not covered by default Objenesis strategies. This example shows a strategy for a Sun 1.4 JVM. ```java public class Sun14Strategy implements InstantiatorStrategy { public ObjectInstantiator newInstantiatorOf(Class type) { // return sun dedicated instantiator return new SunReflectionFactoryInstantiator(type); } } ``` -------------------------------- ### Describe JVM Platform with PlatformDescription Source: https://context7.com/easymock/objenesis/llms.txt Use PlatformDescription to get details about the current JVM environment, including vendor, version, and type. It also provides constants for checking specific JVM types and Java version milestones. ```java import org.objenesis.strategy.PlatformDescription; // Print full platform description System.out.println(PlatformDescription.describePlatform()); // Java 17 (VM vendor name="Oracle Corporation", VM vendor version=17.0.9+11-LTS, // JVM name="Java HotSpot(TM) 64-Bit Server VM", JVM version=17.0.9+11-LTS, JVM info=mixed mode, sharing) // Check JVM type using built-in constants boolean isHotSpot = PlatformDescription.isThisJVM(PlatformDescription.HOTSPOT); // true on Oracle JDK boolean isOpenJDK = PlatformDescription.isThisJVM(PlatformDescription.OPENJDK); // true on OpenJDK boolean isAndroid = PlatformDescription.isThisJVM(PlatformDescription.DALVIK); // true on Android boolean isOpenJDKAndroid = PlatformDescription.isAndroidOpenJDK(); // true on Android N+ // Check Java version milestones boolean isJava9Plus = PlatformDescription.isAfterJigsaw(); // true for Java 9+ boolean isJava11Plus = PlatformDescription.isAfterJava11(); // true for Java 11+ System.out.println("Java spec version: " + PlatformDescription.SPECIFICATION_VERSION); // e.g. "17" System.out.println("JVM name: " + PlatformDescription.JVM_NAME); // e.g. "Java HotSpot..." System.out.println("Android API level: " + PlatformDescription.ANDROID_VERSION); // 0 on non-Android ``` ```java import org.objenesis.instantiator.ObjectInstantiator; import org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator; import org.objenesis.instantiator.sun.UnsafeFactoryInstantiator; import org.objenesis.strategy.InstantiatorStrategy; public class AdaptiveStrategy implements InstantiatorStrategy { @Override public ObjectInstantiator newInstantiatorOf(Class type) { if (PlatformDescription.isThisJVM(PlatformDescription.HOTSPOT) || PlatformDescription.isThisJVM(PlatformDescription.OPENJDK)) { return new SunReflectionFactoryInstantiator<>(type); } return new UnsafeFactoryInstantiator<>(type); // fallback } } ``` -------------------------------- ### Launch benchmark script Source: https://github.com/easymock/objenesis/blob/master/README.md Builds the project with the benchmark profile and then executes the benchmark launch script. ```bash mvn package -Pbenchmark cd benchmark ./launch.sh ``` -------------------------------- ### Full build with Maven Source: https://github.com/easymock/objenesis/blob/master/README.md Executes a comprehensive build including source and Javadoc JAR creation, and SpotBugs analysis. ```bash mvn install -Pfull ``` -------------------------------- ### Generate website with Maven Source: https://github.com/easymock/objenesis/blob/master/README.md Builds the project with the website profile to generate the project website. ```bash mvn package -Pwebsite ``` -------------------------------- ### Find Working Objenesis Instantiators Source: https://github.com/easymock/objenesis/blob/master/website/site/content/details.html Run this command to test and identify which Objenesis instantiators are compatible with your platform. This is useful when Objenesis cannot automatically detect a suitable instantiator. ```bash java -cp objenesis-${project.version}-tck.jar org.objenesis.tck.search.SearchWorkingInstantiator ``` -------------------------------- ### Deploy website Source: https://github.com/easymock/objenesis/blob/master/README.md Script to deploy the project website. Ensure the POM is at the desired release version before execution. ```bash ./deploy-website.sh ``` -------------------------------- ### Use ObjenesisHelper for Static Instantiation Source: https://github.com/easymock/objenesis/blob/master/website/site/content/details.html Demonstrates how to use ObjenesisHelper for creating new instances and obtaining instantiators in a static context. This is a workaround for situations where static methods are unavoidable, though generally discouraged. ```java Object o1 = ObjenesisHelper.newInstance(MyClass.class); Object o2 = ObjenesisHelper.newSerializableInstance(MyClass.class); ObjectInstantiator o3 = ObjenesisHelper.getInstantiatorOf(MyClass.class); ObjectInstantiator o4 = ObjenesisHelper.getSerializableObjectInstantiatorOf(MyClass.class); ``` -------------------------------- ### Use Custom Instantiation Strategy Directly Source: https://github.com/easymock/objenesis/blob/master/website/site/content/details.html Instantiate ObjenesisBase with your custom strategy. This allows Objenesis to use your specialized instantiation logic. ```java Objenesis o = new ObjenesisBase(new Sun14Strategy()); ``` -------------------------------- ### Running Objenesis TCK from Command Line Source: https://context7.com/easymock/objenesis/llms.txt Execute the Objenesis Technology Compatibility Kit (TCK) from the command line to validate instantiator types on the current JVM. Additional JVM flags may be needed for Java 9+. ```bash # Run from command line — no additional classpath needed; Objenesis is bundled java -jar objenesis-3.5-tck.jar # On Java 9+ you may need to add JVM flags if using JPMS-restricted modules: java --add-modules jdk.unsupported \ --add-opens java.base/java.io=org.objenesis \ -jar objenesis-3.5-tck.jar # Search for working instantiators on the current platform java -cp objenesis-3.5-tck.jar org.objenesis.tck.search.SearchWorkingInstantiator ``` -------------------------------- ### Check dependency and plugin updates Source: https://github.com/easymock/objenesis/blob/master/README.md Displays available updates for project dependencies and plugins. ```bash mvn versions:display-dependency-updates versions:display-plugin-updates -Pall ``` -------------------------------- ### Create and Use ObjectInstantiator Source: https://github.com/easymock/objenesis/blob/master/website/site/content/tutorial.html For better performance when creating many objects of the same type, obtain an ObjectInstantiator first. This avoids repeated strategy lookups. ```java Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(MyThingy.class); MyThingy thingy2 = (MyThingy)thingyInstantiator.newInstance(); MyThingy thingy3 = (MyThingy)thingyInstantiator.newInstance(); MyThingy thingy4 = (MyThingy)thingyInstantiator.newInstance(); ``` -------------------------------- ### Using MagicInstantiator and ProxyingInstantiator Source: https://context7.com/easymock/objenesis/llms.txt Demonstrates how to use MagicInstantiator and ProxyingInstantiator to bypass constructor logic. MagicInstantiator uses MagicAccessorImpl, while ProxyingInstantiator creates a dynamic subclass. Note the JVM flags and module requirements for Java 9+. ```java import org.objenesis.instantiator.exotic.MagicInstantiator; import org.objenesis.instantiator.exotic.ProxyingInstantiator; import org.objenesis.instantiator.ObjectInstantiator; // Class with mandatory constructor logic you want to bypass public class HeavyClass { private final Object resource; public HeavyClass() { this.resource = initExpensiveResource(); // we want to skip this } private Object initExpensiveResource() { return new Object(); } public Object getResource() { return resource; } } // --- MagicInstantiator: uses MagicAccessorImpl to skip constructor --- // Requires: --add-modules jdk.unsupported on Java 9+ if sun.misc.Unsafe not available MagicInstantiator magic = new MagicInstantiator<>(HeavyClass.class); HeavyClass obj1 = magic.newInstance(); System.out.println(obj1.getResource()); // null — constructor not called // Access the underlying wrapped instantiator ObjectInstantiator underlying = magic.getInstantiator(); HeavyClass obj2 = underlying.newInstance(); // --- ProxyingInstantiator: creates a dynamic subclass, skips parent constructor --- // Note: requires -Xverify:none JVM flag to pass bytecode verification ProxyingInstantiator proxy = new ProxyingInstantiator<>(HeavyClass.class); HeavyClass obj3 = proxy.newInstance(); // obj3 is actually an instance of HeavyClass$$$Objenesis (a generated subclass) System.out.println(obj3 instanceof HeavyClass); // true System.out.println(obj3.getResource()); // null — parent constructor skipped ``` -------------------------------- ### Build without active profile Source: https://github.com/easymock/objenesis/blob/master/README.md Performs a basic compilation of the application using Maven. ```bash mvn install ``` -------------------------------- ### Generate release notes Source: https://github.com/easymock/objenesis/blob/master/README.md Script to fetch GitHub milestones and issues to generate release notes for a specific version. ```bash # Get the milestone matching the version version=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout | cut -d'-' -f1) milestone=$(curl -s "https://api.github.com/repos/easymock/objenesis/milestones" | jq ".[] | select(.title==\"$version\") | .number") echo "

Version $version ($(date '+%Y-%m-%d'))

" echo echo "
    " curl -s "https://api.github.com/repos/easymock/objenesis/issues?milestone=${milestone}&state=all&per_page=100" | jq -r '.[] | "
  • " + .title + " (#" + (.number|tostring) + ")
  • "' echo "
" ``` -------------------------------- ### ObjenesisStd: Recommended Usage Pattern Source: https://context7.com/easymock/objenesis/llms.txt Use ObjenesisStd as a shared singleton for efficient, thread-safe object instantiation. Obtain reusable instantiators via getInstantiatorOf() for performance benefits when creating multiple instances of the same class. ```java import org.objenesis.*; import org.objenesis.instantiator.ObjectInstantiator; // Usage as a shared singleton (recommended pattern — reuse for caching benefits) public class InstantiationService { private static final Objenesis OBJENESIS = new ObjenesisStd(); public static T createEmpty(Class type) { return OBJENESIS.newInstance(type); } public static ObjectInstantiator getInstantiator(Class type) { return OBJENESIS.getInstantiatorOf(type); } } // Thread-safe concurrent usage Objenesis shared = new ObjenesisStd(); ExecutorService pool = Executors.newFixedThreadPool(4); ObjectInstantiator instantiator = shared.getInstantiatorOf(MyBean.class); for (int i = 0; i < 1000; i++) { pool.submit(() -> { MyBean bean = instantiator.newInstance(); // thread-safe // process bean... }); } ``` -------------------------------- ### Instantiate Object with ObjenesisSerializer Source: https://github.com/easymock/objenesis/blob/master/website/site/content/tutorial.html Use ObjenesisSerializer for instantiation that mimics Java standard serialization. The constructor of the first non-serializable parent class will be called. ```java Objenesis objenesis = new ObjenesisSerializer(); MyThingy thingy1 = (MyThingy) objenesis.newInstance(MyThingy.class); ``` -------------------------------- ### Create Custom Objenesis Implementation Source: https://github.com/easymock/objenesis/blob/master/website/site/content/details.html Extend ObjenesisBase to create a new Objenesis implementation that uses your custom strategy by default. This is useful for encapsulating environment-specific instantiation logic. ```java public class ObjenesisSun14 extends ObjenesisBase { public ObjenesisSun14() { super(new Sun14Strategy()); } } ``` -------------------------------- ### StdInstantiatorStrategy Source: https://context7.com/easymock/objenesis/llms.txt The default JVM-adaptive strategy that automatically selects the best available no-constructor instantiator based on the current JVM environment. ```APIDOC ## StdInstantiatorStrategy — JVM-Adaptive Standard Strategy ### Description `StdInstantiatorStrategy` implements JVM detection logic to pick the best no-constructor instantiator available. It optimizes for different JVMs like HotSpot, OpenJDK, and Android, with `UnsafeFactoryInstantiator` as a fallback. ### Usage Example ```java import org.objenesis.strategy.StdInstantiatorStrategy; import org.objenesis.strategy.PlatformDescription; import org.objenesis.instantiator.ObjectInstantiator; StdInstantiatorStrategy strategy = new StdInstantiatorStrategy(); // The strategy inspects PlatformDescription at runtime System.out.println("Running on: " + PlatformDescription.describePlatform()); // Get a dedicated instantiator for a class ObjectInstantiator inst = strategy.newInstantiatorOf(MyClass.class); MyClass obj = inst.newInstance(); // constructor never called // Throws for primitive types try { strategy.newInstantiatorOf(int.class); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); // handled upstream by ObjenesisBase } ``` ### Platform Detection - Uses `PlatformDescription.describePlatform()` to identify the JVM environment. - Selects appropriate instantiators based on JVM vendor, name, and Android API level. ### Error Handling - Throws `IllegalArgumentException` for primitive types, which is typically handled by `ObjenesisBase`. ``` -------------------------------- ### Add JVM Module Arguments Source: https://github.com/easymock/objenesis/blob/master/website/site/content/details.html Use these arguments when running Objenesis if you encounter NoClassDefFoundError for sun/misc/Unsafe or InaccessibleObjectException due to module restrictions. ```bash --add-modules jdk.unsupported ``` ```bash --add-opens yyy/zzz=org.objenesis ``` -------------------------------- ### Efficient Object Creation with ObjectInstantiator Source: https://context7.com/easymock/objenesis/llms.txt Obtain a reusable ObjectInstantiator once per class for significantly more efficient bulk object creation compared to repeated Objenesis.newInstance() calls. ```java import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import org.objenesis.instantiator.ObjectInstantiator; public class DataTransferObject { public String field1; public int field2; public List items; } Objenesis objenesis = new ObjenesisStd(); // Obtain once, reuse many times ObjectInstantiator dtoFactory = objenesis.getInstantiatorOf(DataTransferObject.class); // Efficient bulk creation — no repeated strategy resolution List batch = new ArrayList<>(100); for (int i = 0; i < 100; i++) { DataTransferObject dto = dtoFactory.newInstance(); dto.field1 = "value-" + i; dto.field2 = i; dto.items = new ArrayList<>(); batch.add(dto); } System.out.println(batch.size()); // 100 System.out.println(batch.get(0).field1); // value-0 ``` -------------------------------- ### Custom Instantiation Strategy with ObjenesisBase Source: https://context7.com/easymock/objenesis/llms.txt Implement a custom InstantiatorStrategy or extend ObjenesisBase directly for specific JVM optimizations. Handles primitive types by throwing an IllegalArgumentException. ```java import org.objenesis.ObjenesisBase; import org.objenesis.instantiator.ObjectInstantiator; import org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator; import org.objenesis.strategy.InstantiatorStrategy; // Custom strategy optimized for a specific JVM/use-case public class HotSpotOnlyStrategy implements InstantiatorStrategy { @Override public ObjectInstantiator newInstantiatorOf(Class type) { return new SunReflectionFactoryInstantiator<>(type); } } // Use directly with ObjenesisBase ObjenesisBase customObjenesis = new ObjenesisBase(new HotSpotOnlyStrategy()); MyClass obj = customObjenesis.newInstance(MyClass.class); // Extend ObjenesisBase for a named implementation public class ObjenesisHotSpot extends ObjenesisBase { public ObjenesisHotSpot() { super(new HotSpotOnlyStrategy()); } public ObjenesisHotSpot(boolean useCache) { super(new HotSpotOnlyStrategy(), useCache); } } ObjenesisHotSpot hotspotObjenesis = new ObjenesisHotSpot(); System.out.println(hotspotObjenesis.toString()); // org.example.ObjenesisHotSpot using HotSpotOnlyStrategy with caching // Primitive types always throw try { hotspotObjenesis.newInstance(int.class); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); // Primitive types can't be instantiated in Java } ``` -------------------------------- ### Run Modernizer plugin Source: https://github.com/easymock/objenesis/blob/master/README.md Executes the Modernizer Maven plugin to check for outdated constructs. ```bash mvn modernizer:modernizer -Pall ``` -------------------------------- ### Standard Object Instantiation with ObjenesisStd Source: https://context7.com/easymock/objenesis/llms.txt Use ObjenesisStd to create instances of classes without calling any constructors. This is useful when constructor logic is expensive or has side effects. Fields will be initialized to their default values (null for objects, 0 for primitives). ```java import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import org.objenesis.instantiator.ObjectInstantiator; // Class with no default constructor public class ComplexService { private final String endpoint; private final int timeout; public ComplexService(String endpoint, int timeout) { this.endpoint = endpoint; this.timeout = timeout; // Expensive initialization, network calls, etc. } public String getEndpoint() { return endpoint; } public int getTimeout() { return timeout; } } // --- Single instantiation --- Objenesis objenesis = new ObjenesisStd(); ComplexService service = objenesis.newInstance(ComplexService.class); // Fields are null/0 — constructor was never called System.out.println(service.getEndpoint()); // null System.out.println(service.getTimeout()); // 0 System.out.println(service instanceof ComplexService); // true // --- Bulk instantiation using a cached ObjectInstantiator (recommended for many objects) --- Objenesis objenesisWithCache = new ObjenesisStd(); // cache enabled by default ObjectInstantiator instantiator = objenesisWithCache.getInstantiatorOf(ComplexService.class); ComplexService s1 = instantiator.newInstance(); ComplexService s2 = instantiator.newInstance(); ComplexService s3 = instantiator.newInstance(); // Each is a distinct, independent instance without any constructor side-effects // --- Disable internal instantiator cache (uncommon — only if class reloading is needed) --- Objenesis noCache = new ObjenesisStd(false); ComplexService s4 = noCache.newInstance(ComplexService.class); ``` -------------------------------- ### Using Shaded Objenesis Source: https://context7.com/easymock/objenesis/llms.txt After shading Objenesis, the API usage remains the same but is accessed under the relocated package namespace. ```java // After shading, the API is the same but under your namespace import com.mylib.internal.objenesis.ObjenesisStd; import com.mylib.internal.objenesis.Objenesis; Objenesis objenesis = new ObjenesisStd(); MyClass obj = objenesis.newInstance(MyClass.class); ``` -------------------------------- ### Update project license Source: https://github.com/easymock/objenesis/blob/master/README.md Formats and updates the project's license headers using the license Maven plugin. ```bash mvn validate license:format -Pall ``` -------------------------------- ### Shading Objenesis with maven-shade-plugin Source: https://context7.com/easymock/objenesis/llms.txt Configure the maven-shade-plugin in pom.xml to relocate the org.objenesis package to avoid dependency conflicts when Objenesis is part of a library JAR. ```xml maven-shade-plugin package shade true org.objenesis:objenesis org.objenesis com.mylib.internal.objenesis ``` -------------------------------- ### SerializingInstantiatorStrategy for Serialization-Mimicking Creation Source: https://context7.com/easymock/objenesis/llms.txt This strategy requires the target class to implement `Serializable`. It invokes the no-arg constructor of the first non-serializable superclass, mimicking Java's deserialization process without triggering `readObject` or `readResolve` callbacks. Attempting to instantiate a non-serializable class will result in an `ObjenesisException` wrapping a `NotSerializableException`. ```java import org.objenesis.ObjenesisBase; import org.objenesis.ObjenesisException; import org.objenesis.strategy.SerializingInstantiatorStrategy; import java.io.Serializable; public class NonSerializableBase { String tag; public NonSerializableBase() { this.tag = "from-base-ctor"; } } public class SerializableChild extends NonSerializableBase implements Serializable { String data; public SerializableChild(String data) { this.data = data; this.tag = "from-child-ctor"; // overrides base } } ObjenesisBase objenesis = new ObjenesisBase(new SerializingInstantiatorStrategy()); SerializableChild child = objenesis.newInstance(SerializableChild.class); System.out.println(child.tag); // "from-base-ctor" — NonSerializableBase() was called System.out.println(child.data); // null — SerializableChild constructor was NOT called // Non-serializable class → throws immediately try { objenesis.newInstance(NonSerializableBase.class); } catch (ObjenesisException e) { System.out.println(e.getCause()); // java.io.NotSerializableException } ``` -------------------------------- ### StdInstantiatorStrategy for JVM-Adaptive Instantiation Source: https://context7.com/easymock/objenesis/llms.txt This strategy automatically detects the JVM environment and selects the most appropriate no-constructor `ObjectInstantiator`. It handles various JVMs like HotSpot, OpenJDK, and Android, with `UnsafeFactoryInstantiator` as a fallback. Primitive types are not supported and will throw an `IllegalArgumentException`. ```java import org.objenesis.strategy.StdInstantiatorStrategy; import org.objenesis.strategy.PlatformDescription; import org.objenesis.instantiator.ObjectInstantiator; StdInstantiatorStrategy strategy = new StdInstantiatorStrategy(); // The strategy inspects PlatformDescription at runtime System.out.println("Running on: " + PlatformDescription.describePlatform()); // e.g. Java 17 (VM vendor name=\"Oracle Corporation\", JVM name=\"Java HotSpot(TM) 64-Bit Server VM\", ...) // Get a dedicated instantiator for a class ObjectInstantiator inst = strategy.newInstantiatorOf(MyClass.class); MyClass obj = inst.newInstance(); // constructor never called // Throws for primitive types try { strategy.newInstantiatorOf(int.class); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); // handled upstream by ObjenesisBase } ``` -------------------------------- ### Upgrade Maven wrapper Source: https://github.com/easymock/objenesis/blob/master/README.md Updates the Maven wrapper scripts to the latest version. ```bash mvn wrapper:wrapper ``` -------------------------------- ### Drop staging repository Source: https://github.com/easymock/objenesis/blob/master/README.md Command to drop a staging repository from Nexus, typically used when a release needs to be aborted. ```bash mvn nexus-staging:drop ``` -------------------------------- ### Discouraged ObjenesisHelper Static API Source: https://context7.com/easymock/objenesis/llms.txt Utilize ObjenesisHelper for static convenience methods, but be aware of potential static state issues in production. Provides methods for standard and Serializable instantiation, and obtaining reusable instantiators. ```java import org.objenesis.ObjenesisHelper; import org.objenesis.instantiator.ObjectInstantiator; import java.io.Serializable; public class MyBean { public String name; } public class MySerializableBean implements Serializable { public String name; } // Standard instantiation (no constructor) MyBean bean = ObjenesisHelper.newInstance(MyBean.class); bean.name = "injected"; System.out.println(bean.name); // injected // Serialization-compliant instantiation (requires Serializable) MySerializableBean sBean = ObjenesisHelper.newSerializableInstance(MySerializableBean.class); // Get reusable instantiators from the shared instances ObjectInstantiator instantiator = ObjenesisHelper.getInstantiatorOf(MyBean.class); MyBean b1 = instantiator.newInstance(); MyBean b2 = instantiator.newInstance(); ObjectInstantiator serInstantiator = ObjenesisHelper.getSerializableObjectInstantiatorOf(MySerializableBean.class); MySerializableBean sb1 = serInstantiator.newInstance(); ``` -------------------------------- ### ObjenesisSerializer: Mimic Deserialization Instantiation Source: https://context7.com/easymock/objenesis/llms.txt Use ObjenesisSerializer to instantiate classes by calling the no-arg constructor of the first non-serializable ancestor, similar to ObjectInputStream.readObject(). The target class must implement java.io.Serializable, otherwise an ObjenesisException is thrown. Serialization callbacks are not invoked. ```java import org.objenesis.Objenesis; import org.objenesis.ObjenesisSerializer; import org.objenesis.instantiator.ObjectInstantiator; import java.io.Serializable; public class BaseEntity { protected long id; public BaseEntity() { this.id = -1L; // Called during serialization-style instantiation System.out.println("BaseEntity no-arg constructor invoked"); } } public class UserAccount extends BaseEntity implements Serializable { private String username; private String email; public UserAccount(String username, String email) { this.username = username; this.email = email; } public String getUsername() { return username; } } // --- Serialization-style instantiation --- Objenesis serializer = new ObjenesisSerializer(); UserAccount account = serializer.newInstance(UserAccount.class); // Output: "BaseEntity no-arg constructor invoked" // username = null, email = null, but id = -1L (set by BaseEntity's constructor) System.out.println(account.getUsername()); // null System.out.println(account.id); // -1 // --- Reusable instantiator for the same class --- ObjectInstantiator accountInstantiator = serializer.getInstantiatorOf(UserAccount.class); UserAccount a1 = accountInstantiator.newInstance(); UserAccount a2 = accountInstantiator.newInstance(); // --- Throws ObjenesisException if class is not Serializable --- try { serializer.newInstance(ComplexService.class); // Not Serializable! } catch (org.objenesis.ObjenesisException e) { System.out.println("Expected: " + e.getCause()); // java.io.NotSerializableException: class ComplexService not serializable } ``` -------------------------------- ### Custom Instantiator Strategies in Objenesis Source: https://context7.com/easymock/objenesis/llms.txt Implement `InstantiatorStrategy` to provide custom object instantiation logic. `AlwaysUnsafeStrategy` forces the use of `UnsafeFactoryInstantiator`, while `AnnotationDrivenStrategy` selects instantiators based on class annotations. ```java import org.objenesis.ObjenesisBase; import org.objenesis.instantiator.ObjectInstantiator; import org.objenesis.instantiator.sun.UnsafeFactoryInstantiator; import org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator; import org.objenesis.strategy.InstantiatorStrategy; // Strategy that always uses Unsafe (fastest on most modern JVMs) public class AlwaysUnsafeStrategy implements InstantiatorStrategy { @Override public ObjectInstantiator newInstantiatorOf(Class type) { return new UnsafeFactoryInstantiator<>(type); } } // Strategy that selects per-class based on annotation or other metadata public class AnnotationDrivenStrategy implements InstantiatorStrategy { private final InstantiatorStrategy stdStrategy = new org.objenesis.strategy.StdInstantiatorStrategy(); @Override public ObjectInstantiator newInstantiatorOf(Class type) { if (type.isAnnotationPresent(UseUnsafe.class)) { return new UnsafeFactoryInstantiator<>(type); } return new SunReflectionFactoryInstantiator<>(type); } } ObjenesisBase objenesis = new ObjenesisBase(new AlwaysUnsafeStrategy()); MyClass obj = objenesis.newInstance(MyClass.class); ``` -------------------------------- ### Set project versions Source: https://github.com/easymock/objenesis/blob/master/README.md Updates project versions across all modules using the versions Maven plugin. ```bash mvn versions:set -DnewVersion=X.Y -Pall mvn versions:commit -Pall ``` -------------------------------- ### ObjenesisSerializer - Serialization-Compliant Instantiation Source: https://context7.com/easymock/objenesis/llms.txt ObjenesisSerializer mimics ObjectInputStream.readObject() by calling the no-arg constructor of the first non-serializable ancestor. It requires the target class to implement java.io.Serializable. ```APIDOC ## ObjenesisSerializer ### Description Mimics `ObjectInputStream.readObject()` by calling the no-arg constructor of the first non-serializable ancestor. Does not invoke serialization callbacks like `readResolve` or `readObject`. The target class must implement `java.io.Serializable` or an `ObjenesisException` wrapping `NotSerializableException` is thrown. ### Usage ```java import org.objenesis.ObjenesisSerializer; import org.objenesis.Objenesis; // Create an ObjenesisSerializer instance Objenesis serializer = new ObjenesisSerializer(); // Instantiate a serializable class UserAccount account = serializer.newInstance(UserAccount.class); // Instantiate a non-serializable class (throws ObjenesisException) try { serializer.newInstance(ComplexService.class); } catch (org.objenesis.ObjenesisException e) { // Handle exception } ``` ### Methods - `newInstance(Class clazz)`: Creates a new instance of the given class using serialization-style instantiation. - `getInstantiatorOf(Class clazz)`: Returns a reusable, cached instantiator for the given class. ``` -------------------------------- ### Objenesis Interface - Core API Contract Source: https://context7.com/easymock/objenesis/llms.txt The Objenesis interface provides the fundamental methods for object instantiation. It is thread-safe and allows for the creation of reusable instantiators. ```APIDOC ## Objenesis Interface ### Description Defines the core methods for Objenesis implementations. It is thread-safe, and both the `Objenesis` instance and its `ObjectInstantiator`s can be shared and used concurrently across multiple threads. ### Methods - ` T newInstance(Class clazz)`: Creates a new instance of the specified class without calling any constructor. - ` ObjectInstantiator getInstantiatorOf(Class clazz)`: Returns a reusable, cached `ObjectInstantiator` dedicated to the given class. ### Usage Example ```java import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import org.objenesis.instantiator.ObjectInstantiator; // Recommended pattern: Use a shared singleton instance Objenesis sharedObjenesis = new ObjenesisStd(); // Create an instance without calling a constructor MyClass instance1 = sharedObjenesis.newInstance(MyClass.class); // Get a reusable instantiator for a specific class ObjectInstantiator instantiator = sharedObjenesis.getInstantiatorOf(MyClass.class); // Use the instantiator to create multiple instances efficiently MyClass instance2 = instantiator.newInstance(); MyClass instance3 = instantiator.newInstance(); ``` ``` -------------------------------- ### AnnotationDrivenStrategy Source: https://context7.com/easymock/objenesis/llms.txt A custom InstantiatorStrategy that selects an instantiator based on class annotations. It defaults to StdInstantiatorStrategy but uses UnsafeFactoryInstantiator if the class is annotated with @UseUnsafe. ```APIDOC ## AnnotationDrivenStrategy ### Description This strategy allows for conditional selection of an `ObjectInstantiator` based on class-level annotations. It provides a flexible way to override default instantiation behavior for specific classes. ### Usage Example ```java import org.objenesis.ObjenesisBase; import org.objenesis.instantiator.ObjectInstantiator; import org.objenesis.instantiator.sun.UnsafeFactoryInstantiator; import org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator; import org.objenesis.strategy.InstantiatorStrategy; // Strategy that selects per-class based on annotation or other metadata public class AnnotationDrivenStrategy implements InstantiatorStrategy { private final InstantiatorStrategy stdStrategy = new org.objenesis.strategy.StdInstantiatorStrategy(); @Override public ObjectInstantiator newInstantiatorOf(Class type) { if (type.isAnnotationPresent(UseUnsafe.class)) { return new UnsafeFactoryInstantiator<>(type); } return new SunReflectionFactoryInstantiator<>(type); } } // Assuming @UseUnsafe is defined elsewhere // ObjenesisBase objenesis = new ObjenesisBase(new AnnotationDrivenStrategy()); // MyClass obj = objenesis.newInstance(MyClass.class); ``` ### Related Classes - `org.objenesis.instantiator.sun.UnsafeFactoryInstantiator` - `org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator` - `org.objenesis.strategy.StdInstantiatorStrategy` ``` -------------------------------- ### AlwaysUnsafeStrategy Source: https://context7.com/easymock/objenesis/llms.txt A custom InstantiatorStrategy that always uses the UnsafeFactoryInstantiator, which is generally the fastest option on modern JVMs. ```APIDOC ## AlwaysUnsafeStrategy ### Description This strategy forces the use of `UnsafeFactoryInstantiator` for creating new objects, bypassing constructors. It's optimized for performance on most contemporary JVMs. ### Usage Example ```java import org.objenesis.ObjenesisBase; import org.objenesis.instantiator.sun.UnsafeFactoryInstantiator; import org.objenesis.strategy.InstantiatorStrategy; // Strategy that always uses Unsafe (fastest on most modern JVMs) public class AlwaysUnsafeStrategy implements InstantiatorStrategy { @Override public ObjectInstantiator newInstantiatorOf(Class type) { return new UnsafeFactoryInstantiator<>(type); } } ObjenesisBase objenesis = new ObjenesisBase(new AlwaysUnsafeStrategy()); MyClass obj = objenesis.newInstance(MyClass.class); ``` ### Related Classes - `org.objenesis.instantiator.sun.UnsafeFactoryInstantiator` - `org.objenesis.ObjenesisBase` ``` -------------------------------- ### Objenesis Interface: Core API Contract Source: https://context7.com/easymock/objenesis/llms.txt The Objenesis interface defines the core methods for object instantiation. Implementations are thread-safe and can be shared. Use newInstance() to create an instance without calling constructors, or getInstantiatorOf() to obtain a reusable, cached instantiator for a specific class. ```java package org.objenesis; import org.objenesis.instantiator.ObjectInstantiator; public interface Objenesis { // Creates a new instance without calling any constructor T newInstance(Class clazz); // Returns a reusable, cached instantiator dedicated to the given class ObjectInstantiator getInstantiatorOf(Class clazz); } ``` -------------------------------- ### Handle Instantiation Errors with ObjenesisException Source: https://context7.com/easymock/objenesis/llms.txt ObjenesisException wraps exceptions during instantiation. It's an unchecked exception, allowing it to propagate or be caught and handled, providing specific error information through its cause. ```java import org.objenesis.Objenesis; import org.objenesis.ObjenesisSerializer; import org.objenesis.ObjenesisException; Objenesis serializer = new ObjenesisSerializer(); // Pattern 1: Let it propagate (unchecked) public Object deserializeEmpty(Class type) { return serializer.newInstance(type); // throws ObjenesisException if not Serializable } ``` ```java import org.objenesis.Objenesis; import org.objenesis.ObjenesisSerializer; import org.objenesis.ObjenesisException; Objenesis serializer = new ObjenesisSerializer(); // Pattern 2: Catch and handle public T tryInstantiate(Class type) { try { return serializer.newInstance(type); } catch (ObjenesisException e) { Throwable cause = e.getCause(); if (cause instanceof java.io.NotSerializableException) { System.err.println("Class is not serializable: " + type.getName()); } else { System.err.println("Instantiation failed: " + cause); } return null; } } ``` ```java import org.objenesis.Objenesis; import org.objenesis.ObjenesisSerializer; import org.objenesis.ObjenesisException; import java.io.Serializable; Objenesis serializer = new ObjenesisSerializer(); // Pattern 3: Defensive check before instantiation public T safeSerializingInstantiate(Class type) { if (!Serializable.class.isAssignableFrom(type)) { throw new IllegalArgumentException(type + " must implement Serializable"); } return serializer.newInstance(type); } ``` -------------------------------- ### SerializingInstantiatorStrategy Source: https://context7.com/easymock/objenesis/llms.txt A strategy that ensures the target class implements Serializable and mimics Java's deserialization process to instantiate objects without calling constructors. ```APIDOC ## SerializingInstantiatorStrategy — Serialization-Mimicking Strategy ### Description This strategy enforces that the target class implements `Serializable`. It then instantiates objects by invoking the no-arg constructor of the first non-serializable superclass, replicating Java's deserialization behavior without triggering `readObject` or `readResolve` callbacks. ### Usage Example ```java import org.objenesis.ObjenesisBase; import org.objenesis.ObjenesisException; import org.objenesis.strategy.SerializingInstantiatorStrategy; import java.io.Serializable; public class NonSerializableBase { String tag; public NonSerializableBase() { this.tag = "from-base-ctor"; } } public class SerializableChild extends NonSerializableBase implements Serializable { String data; public SerializableChild(String data) { this.data = data; this.tag = "from-child-ctor"; // overrides base } } ObjenesisBase objenesis = new ObjenesisBase(new SerializingInstantiatorStrategy()); SerializableChild child = objenesis.newInstance(SerializableChild.class); System.out.println(child.tag); // "from-base-ctor" — NonSerializableBase() was called System.out.println(child.data); // null — SerializableChild constructor was NOT called // Non-serializable class → throws immediately try { objenesis.newInstance(NonSerializableBase.class); } catch (ObjenesisException e) { System.out.println(e.getCause()); // java.io.NotSerializableException } ``` ### Requirements - The target class must implement `java.io.Serializable`. ### Behavior - Instantiates objects by calling the no-argument constructor of the first non-serializable superclass. - Does not invoke the constructor of the target class itself. - Does not trigger `readObject` or `readResolve` methods. ### Error Handling - Throws `ObjenesisException` (wrapping `NotSerializableException`) if the target class does not implement `Serializable`. ``` -------------------------------- ### Maven Shade Plugin for Embedding Objenesis Source: https://github.com/easymock/objenesis/blob/master/website/site/content/embedding.html Configure the Maven Shade Plugin to include Objenesis and relocate its packages. This prevents naming collisions by renaming the Objenesis classes to a specified shaded pattern. ```xml maven-shade-plugin package shade true org.objenesis:objenesis org.objenesis org.easymock.classextension.internal.objenesis ``` -------------------------------- ### Rollback release with Maven Source: https://github.com/easymock/objenesis/blob/master/README.md Commands to rollback a Maven release, delete the Git tag, and reset the commit history. ```bash mvn release:rollback -Pall git tag -d $version git push origin :refs/tags/$version git reset --hard HEAD~2 ``` -------------------------------- ### Maven Dependency for Objenesis Source: https://context7.com/easymock/objenesis/llms.txt Add Objenesis to your Maven project by including the appropriate dependency in your pom.xml. The 'objenesis-exotic' artifact is for advanced instantiators. ```xml org.objenesis objenesis 3.5 org.objenesis objenesis-exotic 3.5 ``` -------------------------------- ### Jarjar Ant Task for Embedding Objenesis Source: https://github.com/easymock/objenesis/blob/master/website/site/content/embedding.html Use this Ant task to package Objenesis classes with your project, renaming them to avoid conflicts. Ensure the 'rule' pattern matches the Objenesis package and 'result' specifies the new package. ```xml ``` -------------------------------- ### Disable Objenesis Cache Source: https://github.com/easymock/objenesis/blob/master/website/site/content/details.html Instantiate ObjenesisStd with 'false' to disable the built-in ObjectInstantiator cache. This can be useful in specific scenarios, though the cache is generally recommended for performance. ```java Objenesis o = new ObjenesisStd(false); // cache disabled ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.