The no-argument constructor is a
requirement (tools like Hibernate use
reflection on this constructor to
instantiate objects).
I got this hand-wavy answer but could somebody explain further? Thanks
Hibernate, and code in general that creates objects via reflection use Class<T>.newInstance() to create a new instance of your classes. This method requires a public no-arg constructor to be able to instantiate the object. For most use cases, providing a no-arg constructor is not a problem.
There are hacks based on serialization that can work around not having a no-arg constructor, since serialization uses jvm magic to create objects without invoking the constructor. But this is not available across all VMs. For example, XStream can create instances of objects that don't have a public no-arg constructor, but only by running in a so-called "enhanced" mode which is available only on certain VMs. (See the link for details.) Hibernate's designers surely chose to maintain compatibility with all VMs and so avoids such tricks, and uses the officially supported reflection method Class<T>.newInstance() requiring a no-arg constructor.
Erm, sorry everyone, but Hibernate does not require that your classes must have a parameterless constructor. The JPA 2.0 specification requires it, and this is very lame on behalf of JPA. Other frameworks like JAXB also require it, which is also very lame on behalf of those frameworks.
(Actually, JAXB supposedly allows entity factories, but it insists on instantiating these factories by itself, requiring them to have a --guess what-- parameterless constructor, which in my book is exactly as good as not allowing factories; how lame is that!)
But Hibernate does not require such a thing.
Hibernate supports an interception mechanism, (see "Interceptor" in the documentation,) which allows you to instantiate your objects with whatever constructor parameters they need.
Basically, what you do is that when you setup hibernate you pass it an object implementing the org.hibernate.Interceptor interface, and hibernate will then be invoking the instantiate() method of that interface whenever it needs a new instance of an object of yours, so your implementation of that method can new your objects in whatever way you like.
I have done it in a project and it works like a charm. In this project I do things via JPA whenever possible, and I only use Hibernate features like the interceptor when I have no other option.
Hibernate seems to be somewhat insecure about it, as during startup it issues an info message for each of my entity classes, telling me INFO: HHH000182: No default (no-argument) constructor for class and class must be instantiated by Interceptor, but then later on I do instantiate them by interceptor, and it is happy with that.
To answer the "why" part of the question for tools other than Hibernate, the answer is "for absolutely no good reason", and this is proven by the existence of the hibernate interceptor. There are many tools out there that could have been supporting some similar mechanism for client object instantiation, but they don't, so they create the objects by themselves, so they have to require parameterless constructors. I am tempted to believe that this is happening because the creators of these tools think of themselves as ninja systems programmers who create frameworks full of magic to be used by ignorant application programmers, who (so they think) would never in their wildest dreams have a need for such advanced constructs as the... Factory Pattern. (Okay, I am tempted to think so. I don't actually think so. I am joking.)
Hibernate instantiates your objects. So it needs to be able to instantiate them. If there isn't a no-arg constructor, Hibernate won't know how to instantiate it, i.e. what argument to pass.
The hibernate documentation says:
4.1.1. Implement a no-argument constructor
All persistent classes must have a default constructor (which can be non-public) so that Hibernate can instantiate them using Constructor.newInstance(). It is recommended that you have a default constructor with at least package visibility for runtime proxy generation in Hibernate.
The hibernate is an ORM framework which supports field or property access strategy. However, it does not support constructor-based mapping - maybe what you would like ? - because of some issues like
1º What happens whether your class contains a lot of constructors
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) { ... }
public Person(String name) { ... }
public Person(Integer age) { ... }
}
As you can see, you deal with a issue of inconsistency because Hibernate cannot suppose which constructor should be called. For instance, suppose you need to retrieve a stored Person object
Person person = (Person) session.get(Person.class, <IDENTIFIER>);
Which constructor should Hibernate call to retrieve a Person object ? Can you see ?
2º And finally, by using reflection, Hibernate can instantiate a class through its no-arg constructor. So when you call
Person person = (Person) session.get(Person.class, <IDENTIFIER>);
Hibernate will instantiate your Person object as follows
Person.class.newInstance();
Which according to API documentation
The class is instantiated as if by a new expression with an empty argument list
Moral of the story
Person.class.newInstance();
is similar To
new Person();
Nothing else
Hibernate needs to create instances as result of your queries (via reflection), Hibernate relies on the no-arg constructor of entities for that, so you need to provide a no-arg constructor. What is not clear?
Actually, you can instantiate classes which have no 0-args constructor; you can get a list of a class' constructors, pick one and invoke it with bogus parameters.
While this is possible, and I guess it would work and wouldn't be problematic, you'll have to agree that is pretty weird.
Constructing objects the way Hibernate does (I believe it invokes the 0-arg constructor and then it probably modifies the instance's fields directly via Reflection. Perhaps it knows how to call setters) goes a little bit against how is an object supposed to be constructed in Java- invoke the constructor with the appropriate parameters so that the new object is the object you want. I believe that instantiating an object and then mutating it is somewhat "anti-Java" (or I would say, anti pure theoretical Java)- and definitely, if you do this via direct field manipulation, it goes encapsulation and all that fancy encapsulation stuff.
I think that the proper way to do this would be to define in the Hibernate mapping how an object should be instantiated from the info in the database row using the proper constructor... but this would be more complex- meaning both Hibernate would be even more complex, the mapping would be more complex... and all to be more "pure"; and I don't think this would have an advantage over the current approach (other than feeling good about doing things "the proper way").
Having said that, and seeing that the Hibernate approach is not very "clean", the obligation to have a 0-arg constructor is not strictly necessary, but I can understand somewhat the requirement, although I believe they did it on purely "proper way" grounds, when they strayed from the "proper way" (albeit for reasonable reasons) much before that.
It is much easier to create object with a parameterless constructor through reflection, and then fill its properties with data through reflection, than to try and match data to arbitrary parameters of a parameterized constructor, with changing names/naming conflicts, undefined logic inside constructor, parameter sets not matching properties of an object, et cetera.
Many ORMs and serializers require parameterless constructors, because paramterized constructors through reflection are very fragile, and parameterless constructors provide both stability to the application and control over the object behavior to the developer.
Hibernate uses proxies for lazy loading. If you do no define a constructor or make it private a few things may still work - the ones that do not depend on proxy mechanism. For example, loading the object (with no constructor) directly using query API.
But, if you use session.load method() you'll face InstantiationException from proxy generator lib due to non-availability of constructor.
This guy reported a similar situation:
http://kristian-domagala.blogspot.com/2008/10/proxy-instantiation-problem-from.html
Check out this section of the Java language spec that explains the difference between static and non-static inner classes: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.1.3
A static inner class is conceptually no different than a regular general class declared in a .java file.
Since Hibernate needs to instantiate ProjectPK independantly of the Project instance, ProjectPK either needs to be a static inner class, or declared in it's own .java file.
reference org.hibernate.InstantiationException: No default constructor
In my case, I had to hide my no-arg constructor, but because Hibernate I couldn't do it. So I solved the problem in another way.
/**
* #deprecated (Hibernate's exclusive constructor)
*/
public ObjectConstructor (){ }
Summarizing of what is below. It matters if you want to be JPA compatible or strictly Hibernate
Just look at official documentation: https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#entity-pojo
Section 2.1 The Entity Class of the JPA 2.1 specification defines its requirements for an entity class. Applications that wish to remain portable across JPA providers should adhere to these requirements:
One point says:
The entity class must have a public or protected no-argument
constructor. It may define additional constructors as well.
However, hibernate is less strict in this:
Hibernate, however, is not as strict in its requirements. The differences from the list above include:
One point says:
The entity class must have a no-argument constructor, which may be
public, protected or package visibility. It may define additional
constructors as well.
More on that is right below:
https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#entity-pojo-constructor
JPA requires that this constructor be defined as public or protected. Hibernate, for the most part, does not care about the constructor visibility, as long as the system SecurityManager allows overriding the visibility setting. That said, the constructor should be defined with at least package visibility if you wish to leverage runtime proxy generation.
I would like to use a CGLIB proxy to add my own reusable equals() method to existing objects.
The objects do not necessarily implement any interfaces and I need to be able to cast the proxied object to the original class (without getting the target of the proxy).
Unfortunately, it seems that CGLIB implements its own equals() method and makes sure that only that method is called: there is a private static class (EqualsInterceptor) whose method intercept() implements a reasonable logic to compare proxied objects.
The problem is that this method, at the end, delegates the comparison to the target objects: I need instead to reuse some logic that is not implemented by the target classes.
Using a standard proxy, I was able to intercept the call to the equals() method and execute my logic. The problem is that these kind of proxies cannot be cast to the original class.
It seems that the only way is to rewrite some classes in the CGLIB library. It does not seem a good idea.
No, this is not possible using cglib.
You can use another library such as Byte Buddy which allows you to intercept equals/hashCode just like any other method.
For disclosure: I am the author of Byte Buddy and a maintainer for cglib which are both Apache 2.0 licensed.
I was going through the documentation for hibernate and found these lines
The no-argument constructor is a requirement for all persistent
classes; Hibernate has to create objects for you, using Java
Reflection. The constructor can be private, however package or public
visibility is required for runtime proxy generation and efficient data
retrieval without bytecode instrumentation
Can anyone please explain the runtime proxy generation and efficient data retrieval without bytecode instrumention
Runtime proxy means that Hibernate will wrap your class with a Proxy class. You can see in debugger, that instantiated objects are not of your type but of some proxy one.
To do so, Hibernate needs to override your class. The parameterless constructor is needed to call base() constructor. Hibernate doesn't know how to fill your custom parameters. Other think is to make all your properties and methods virtual so they can be overridden too.
Think of it like you have third party library (one containing your persistent classes) and now you need to add some general functionality to them, without reading the doc and analyzing class by class, property by property.
I want to listen on method calls in order to attach additional behavior dynamically around the call. I've already done it on JUnit methods with a custom annotation and runner. I'm trying to do it on a standard java application.
The main idea is to do:
#Override
public void beforeInvoke (Object self, Method m, Object[] args){
Object[] newargs = modifyArgs (args);
m.invoke (self, newargs);
}
It's just an abstract idea, I don't have any concrete example, but I'm curious if it's possible in java.
I've found some approaches:
java.lang.reflect.Proxy.newProxyInstance(...)
where a proxy is defined for an interface only (but not used to decorate concrete classes). It seems similar to injection pattern and it's a different concern.
Another approach here using a factory pattern with the ProxyFactory class. This other solution requires explicit calls to create() method to produce object proxies listening on method invocations. So, if you bypass it by using natural constructors of your classes, it's not working. It's very constraining if you must explicit a call to a factory each time you have to create an object.
There is a way to do it with transparency ?
Like Proxy.newProxyInstance() but working also on concrete classes ?
Thanks.
Well,this is commonly seen with Spring Framework and Aspect Oriented Programming. Since you delegate your constructor calls to Spring, it is quite easy for Spring to put a proxy in place to intercept calls to the actual objects.
As far as I can tell, the only way to intercept calls is to use a proxy. Either in the way you mentioned or using Spring and AOP.
I think cglib let you instrument concrete classes.
As far as I know there is no easy way to intercept method calls that are called on a concrete class.
As mentioned you could manipulate the bytecode during compilation (as Used in AOP) or at class loading time (as used from cglib).
Another product to instrument Classes would be jmockit (http://jmockit.org/). Usually I would use this special kind of black magic only in testing environments and not in an productive environment.
Another way you could go is Annotation Processing. It work's during compiling process. You have to write a Processor which will walk through your source code and generate source-code that contains the original code plus the enhanced method-calls you need.
Depending on how much source-code you have to enhance, this method might be a good idea, but in general it is a lot of work.
Here's a link (https://deors.wordpress.com/2011/10/08/annotation-processors/).
Despite usually it's used in combination with annotations, this is not a strict requirement.
I'm now reading a Spring book written in Korean language and my English is bad. Please understand it.
In the book, it says Spring's AOP initiates class using Dynamic proxy if it uses Interface and it uses CGLIB to initiate class in case of not using Interface.
I don't clearly understand what it means. could you help me understand its deep meaning.
I don't know this question is silly or not. but I'm just curious THX.
A proxy is essentially a mediator between a client and an object such that it implements the object's non-final methods. Proxying an interface is relatively straightforward since an interface is simply a list of methods which need to be implemented, facilitating the interception of method invocations.
The Proxy class in Java is a class that implements a list of interfaces which are specified at runtime. A proxy then has an InvocationHandler associated with it, which delegates method calls made on the proxy to the object being proxied. It acts as a level of indirection such that methods are not invoked on the object itself but rather on its proxy. The InvocationHandler has but a single method which needs to be implemented:
public Object invoke(Object proxy, Method method, Object[] args)
Meanwhile, the client invoking the method can't tell the difference between a proxy and its underlying object representation, nor should it care.
Proxying a class dynamically, as opposed to an interface, is not quite as simple. While Java's Proxy is merely a runtime implementation of an interface or set of interfaces, objects do not have to implement an interface. Therefore, proxying classes requires bytecode generation, which is where libraries such as cglib come into play. cglib provides support for proxying classes because it can dynamically generate bytecode (i.e. class files), meaning it can extend classes at runtime in a way that Java's Proxy can implement an interface at runtime.
There are many uses of proxies. One such use is in lazy loading. Lazy loading allows objects in an object graph to be loaded only when they are needed. Rather than loading them all into memory immediately, which could be expensive and resource-intensive, we can load them on-the-fly when we need to access them, such as iterating over a collection of objects. Instead of loading the entire collection, we simply load a small set at a time. This can be achieved with proxies. The proxy represents the lazily-loaded object. The object itself, which might be loaded from a database, is not loaded until a method is invoked on its proxy. The proxy, which intercepts the method invocation, will then load the object into memory and delegate the method invocation to it.
Here is an example of a lazy-loading implementation:
public abstract class LazilyLoadedObject implements InvocationHandler {
private Object target;
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (target == null) {
target = loadObject();
}
return method.invoke(target, args);
}
/**
* Loads the proxied object. This might be an expensive operation
* or loading lots of objects could consume a lot of memory, so
* we only load the object when it's needed.
*/
protected abstract Object loadObject();
}
The above InvocationHandler would be passed to a proxy so that methods invoked on the proxy would be handled by the InvocationHandler. The handler checks to see if the object has been loaded. If it hasn't, it will call loadObject(), which could be some sort of database query that retrieves the object.
Proxies are very powerful because they allow for the interception of method invocations. Such is the case in AOP.
Java Dynamic Proxy is a reflective element of the Java language that allows a user to create a proxy of an interface at runtime. Being a part of the reflection package, it is a part of Java and it ships with the JRE/JDK.
CGLIB is a code generation library which has the capability to extend Java classes at runtime. Because of this, Spring utilizes this functionality to proxy non-interfaces for its AOP library.