How to Instantiate Java Objects Without Constructors Using Objenesis
This tutorial explains how Objenesis enables Java objects to be instantiated without invoking constructors, covering traditional object creation, the library’s internal mechanisms, Maven setup, usage examples with ObjenesisStd, ObjenesisSerializer, and ObjenesisHelper, advanced scenarios, best practices, and considerations for safe adoption.
Traditional Object Creation in Java
When using the new keyword, Java invokes a constructor. Example:
public class User {
private String name;
public User() {
System.out.println("User constructor is called!");
}
// getters and setters
}Creating an instance: User user = new User(); Output confirms that the constructor is executed.
How Objenesis Works
Objenesis bypasses new and constructors by using low‑level JVM mechanisms to allocate memory and instantiate objects. It tries several strategies depending on the JVM vendor and version.
Setup
Add the Maven dependency:
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>3.4</version>
</dependency>Two main implementations are provided:
ObjenesisStd – thread‑safe, tries multiple strategies.
ObjenesisSerializer – non‑thread‑safe, optimized for deserialization frameworks.
ObjenesisHelper simplifies usage of these implementations.
Creating Objects with ObjenesisStd
Modify the class to prevent constructor use:
public class User implements Serializable {
private String name;
public User() {
throw new RuntimeException("User constructor should not be called!");
}
// getters and setters
}Instantiate without calling the constructor:
Objenesis objenesis = new ObjenesisStd();
User user = objenesis.newInstance(User.class);
assertNotNull(user);
user.setName("Harry Potter");
assertEquals("Harry Potter", user.getName());Creating Objects with ObjenesisSerializer
Use the serialization‑based strategy (class must implement Serializable):
Objenesis objenesis = new ObjenesisSerializer();
User user = objenesis.newInstance(User.class);
assertNotNull(user);
user.setName("Harry Potter");
assertEquals("Harry Potter", user.getName());Using ObjenesisHelper
ObjenesisHelper provides static shortcuts for both standard and serializable strategies:
User user = ObjenesisHelper.newInstance(User.class);
assertNotNull(user);
user.setName("Harry Potter");
assertEquals("Harry Potter", user.getName());
User user2 = ObjenesisHelper.newSerializableInstance(User.class);
assertNotNull(user2);
user2.setName("Harry Potter");
assertEquals("Harry Potter", user2.getName());Advanced Use Cases
Serialization frameworks like Kryo use Objenesis to create objects during deserialization without invoking constructors.
Mocking frameworks such as Mockito and EasyMock rely on Objenesis to generate proxy instances for tests.
Objenesis can instantiate final classes or classes with private constructors, bypassing reflection limitations.
Lightweight DI containers may use Objenesis for property‑based injection when constructor injection is impractical.
Performance‑critical code can clone or reuse objects by creating a fresh instance and manually populating fields, avoiding costly constructor logic.
Best Practices
Prefer normal constructors; use Objenesis only when necessary.
Be aware of security restrictions; environments with a Java Security Manager may block Objenesis.
Let frameworks handle Objenesis internally rather than invoking it directly.
Handle uninitialized fields carefully to avoid unexpected behavior.
Thoroughly test objects created via Objenesis to ensure state and behavior remain correct.
Document the usage clearly for future maintainers.
Conclusion
Objenesis offers a powerful way to instantiate Java objects without running constructors, making it valuable for serialization, mocking, and proxy frameworks. However, it should be used judiciously to avoid side effects and maintainability issues.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
