I am trying to write a constructor that creates an instance of a class from an already existing instance of a super class; I am aware of aggregation - I could have created a field of type MyClass - but I do not want to use it. So what I do is take each field in turn and initialize it, like below:
public MyClassExtension extends MyClass
{
Object new_field;
public MyClassExtension(MyClass instance)
{
this.field_1 = instance.field_1;
this.field_2 = instance.field_2;
......
this.field_20= instance.field_20;
this.new_field= some_value;
}
}
The problem is that this approach is pretty verbose. Is there a shorter form of achieving the same result?
Attempts:
calling
super(instance)
gives 'the constructor is undefined' error; indeed, there is no such constructor; even if I created it, the same question applies to that constructorcalling
this(instance)
gives 'recursive constructor invocation' error, which is normal, since I am calling a method from within itself with no stop condition
Context information: MyClass is a javax.persistence.Entity
, thus the large number of fields.
MyClassExtension adds some booleans that store the visibility of UI elements, depending on the data.
Note: I am constrained to use this approach by the technology stack. Prior to EL 2.2 I cannot call a backend method from JSF, to determine the visibility of a UI element. see: How to call a method with a parameter in JSF
EDIT: I have read Copy constructor using reflection, but none of the answers is applicable to me:
first answer: I cannot introduce an external library in an existing project without the approval of my manager; I need a core Java functionality
second answer: I have already tried
super()
- see above - I won't duplicate my explanation