2

I am trying to make a serialization of some java objects. For that I would like to instantiate (to me) unknown classes, which might not have a default constructor. As I can not know how the other constructors should be called (i can know the parameters, yes, but thats not very helpful), I would like to just create a "blank" instance of a class.

Afterwards I would use reflection to set it's attributes.

Is this somehow possible?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Blub
  • 3,762
  • 1
  • 13
  • 24

2 Answers2

6

It is possible using the Unsafe class. Additionally there is possibility to obtain a "constructorForSerialization" using this sun.x class:

ReflectionFactory.getReflectionFactory().
    newConstructorForSerialization(clazz, c);
anastaciu
  • 23,467
  • 7
  • 28
  • 53
R.Moeller
  • 3,436
  • 1
  • 17
  • 12
1

In short, no.

However, you can call a constructor in many various ways. It may be a "default" constructor, or a constructor that is not actually expressed in your code, or a constructor that is internal when doing other items, like deserializing.

A constructor returns a reference, and that consists of a few important internal steps.

  1. The JVM needs to allocate memory on the heap to hold the member data of the Class (and references to supporting items).
  2. The address of that internal JVM data structure is given a type-safe reference.
  3. The appropriate <init>(...) method is called (From the programming side of things, this is what people think of as a Constructor Method, typcially written public Object(...) { ... }).
  4. The reference is returned to the execution context.

So construction is more than just the code you call, it is the implementation of Object creation. You can avoid supplying init methods by various means, but the internal operations required for construction aren't really skippable. If they were, then you would lack the object reference.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138