DeSerialization using the Serializable interface mechanism uses Reflection to deserialize the Object bytes to Object. But default no arg constructor is not called during this process and hence its not needed. But all the frameworks like Spring,Hibernate etc need no arg constructor even though they use Reflection. Isn't this contradictory or am I missing something?
The builtin standard deserialization does not use standard reflection to create instances.
Standard reflection can not create instances without calling a constructor (not necessarily the no arg constructor). So any framework only using standard reflection will need to call a constructor for instance creation.
To create instances without calling a constructor you need some kind of jvm-vendor specific extension, like Unsafe. It is up to the framework developers to use these extensions, many decide against it. (XStream https://x-stream.github.io/faq.html is the only i am aware of that actually uses it)
Related
I've just discovered about the existence of the Method class in Java.
Is an instance of this class equivalent to an instance of a Command class in the context of the Command design pattern?
If not, what are this class' practical uses?
Is an instance of this class equivalent to an instance of a Command class in the context of the Command design pattern?
No, absolutely not: Method class is part of reflection feature of Java. Command pattern, on the other hand, is language-agnostic, so it can be implemented in any language, including ones that lack reflection capabilities.
The practical use of the Method class is to access methods of classes to which you do not have access at compile time. You can load a class by name, grab its method object - also by name, and perform an invocation.
With this said, it does not mean that you couldn't implement something that behaves like the command pattern using reflection. In fact, you could make your implementation more flexible by eliminating compile-time dependency on your code. For example, you could build a system that take plugins, and requires that plugin classes implement a particular method. Rather than shipping to plugin writers an interface with the signature of the method, you could tell them that as long as their class implements the method that you need, the plugin is going to be accepted. At runtime you would be able to discover the proper method through reflection, and call user code without compile-time dependencies on either side.
This class, as well as the class Field, class Class, are all part of reflection API. This API is used to provide access to object in an indirect way.
The first idea behind reflection was to allow an object to describe itself. For instance an IDE could display all properties of an object for debugging, RAID development and so on.
If reflection is still used that way, it's also used today to discover dynamically the structure of an object or a class and "act on" it without explicitly knowing it : to change the values of its fields or invoke one its methods.
For instance, if you know class A, you can invoke the method m() of A this way :
A a = new A();
a.m();
With reflection, without knowing class A explicitly, you could :
Object a = A.getDeclaredConstructors()[0].newInstance();
Method m = a.getClass().getMethod("m");
m.invoke(a, null);
In the second case, you can imagine a more generic mechanism where you discover methods or fields and invoke them or change their values without knowing them in advance.
So, to answer directly your question, it has nothing to do with the Command design pattern.
I'm pretty new to java, and on the java tutorial it uses the terms "class literal" and "reflection".
From the reflection api trail from the java website, http://docs.oracle.com/javase/tutorial/reflect/index.html, it says
Extensibility Features
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
What does that mean?
Thanks.
A class literal is something like String.class, i.e. a compile-time literal representing the String class.
In short, reflection is a language feature that allows you to "reflect" on the code, i.e. you can query the system for classes, methods, fields, etc. and use that data to create new instances, call methods or change the value of fields.
Reflection might be useful to create objects of classes that are not known at compile-time, but are on the classpath at runtime. Several extension frameworks make use of that, mostly by providing fully qualified class names in some text file (e.g. com.acme.SomeFancyClass), getting the associated Class object from the class loader and creating new instances.
Other frameworks (e.g. Apache Common's builder objects, OGNL, Java Beans etc.) use reflection to query the available properties (getters and/or matching setters) that can be accessed (through calls to those getters/setters).
However, if you are new to Java, I'd recommend diving into other language features before loosing yourself in the depth of the reflection facility.
I have a package which has some N number of classes and I'm scanning all the classes and initializing them through a method. All the classes with a default constructor are being initialized but the ones without default(zero argument) constructor throws an exception. Does anyone know how to create an object without default constructor?
P.S. I need a java code.
Use Class#getConstructors() to find a defined constructor, and call that instead.
You can try looking here. It explains how to create objects using Java reflection.
Or just Google: java constructor reflection. I got this one using the "I'm feeling lucky" feature
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 am involved in this project where we are building on good bit of legacy code. I have a particular situation about one big java bean object which has to be transferred over wire. So my first thought was to make it immutable and serializable to do the trick .At this point I am faced with a few difficult choices :-
Ideally I want some way to
automatically generate an immutable,
serializable version of this class.
I dont have the scope to refactor or
alter this class in any way and i
would really really hate to have to
copy paste the class with a
different name ?
Assuming that i gave up on 1 i.e i
actually chose to duplicate code of
the HUGE javabean class , i still
will be in the unsavoury situation
of having to write a constructor
with some 20-25 parameters to make
this class immutable. what is a
better way to make a class immutable
other than constructor injection ?
Thanks and Regards,
To make it truly immutable, you need to initialize the members at construction time.
One way (and I ain't sayin' it's pretty!) to do this and avoid a huge parameter list in the constructor is to have a mutable type that has the same properties. Set the the properties on the mutable type one at a time, through "setters", then pass the mutable object to the constructor of the immutable type as a single argument. The immutable object then copies the properties from the mutable source to it's own (final) members.
You might also consider "effective immutability". That is, even though immutability is not enforced by the system, you use coding practices that clearly separate the initialization phase from the usage phase. After all, immutability is not required for serialization.
You can take this a step further, creating an implementation-hiding wrapper for the interface that doesn't expose the properties of the implementation. The wrapper only implements the methods in the interface, by delegating to the "real" implementation. The setters and getters from the implementation are not present in the wrapper. This will stop clients from simply down-casting from the interface to the implementation class and manipulating the properties.
Joshua Bloch's "Effective Java" illustrates the Builder pattern, where simple Builder objects are used to construct a complex object with a long constructor argument list. I'd recommend it.
http://www.drdobbs.com/java/208403883;jsessionid=PJWS41F5DJ4QRQE1GHRSKH4ATMY32JVN?pgno=2
20-25 properties is not huge for a one off, particularly if you are using a half-decent editor.
If you already have a mutable instance when constructing the immutable version, just pass that to the constructor.
If you want to be really evil hacky, use java.beans to create a serialisable Map for the mutable class or subclass implementing Externalizable. Alternatively you could use java.beans XML serialisation (the XML than can be sent over Java serialisation...).
What about a simple read only interface cotaining the getters?
If the bean class is your own, let it simpley implement the interface and use just the interface after creation.
If you have no control over the bean class, you can also create a getter interface and implement it by creating a proxy for the getter interface with an invokation handler delegating all method calls to the bean.
Step 1: Create a new class and give it instance variables with the exact same names as the instance variables of your 'big java bean object'. That new class should not have setters (but getters only) to make it immutable.
Step 2: Use Apache Commons BeanUtils.copyProperties to copy all the properties (i.e. instance variables) from your 'big java bean object' to your new object.
A few ideas:
Protected setters and factory methods
You can define beans with protected setter methods and in the same package, a factory class that takes all the parameters and calls those setters. The bean is immutable outside that package. To enforce this, be sure to seal your jar so end users cannot create new classes in the same package.
Note: You can use my JavaDude Bean annotations to make the creation simpler:
http://code.google.com/p/javadude/wiki/Annotations
For example:
#Bean(writer=Access.PROTECTED, // all setXXX methods will be protected
properties={
#Property(name="name"),
#Property(name="age", type=int.class)
})
public class Person extends PersonGen {
}
Creating getters and a constructor in eclipse
Eclipse has some nice tools to make this fast:
Create the bean class
Add the fields you want
Right-click in the editor window
Choose Source->Generate Getters and Setters
Press the "Select getters" button
Press ok
Right-click in the editor window
Choose Source->Generate Constructors from fields
Pick and order the fields you want in the constructor
Press ok
Immutability Decorator
Another idea is to define your bean with getters and setters (you can use the above technique but include setters), then you can create a wrapper class for it that only has the getters.