Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standardising a java constructor for use by reflection

Tags:

java

I have a PropertyBag class which models a set of properties consumable by objects.

I also have several classes A1, A2, ..., AN that have constructors of the form

public A...(PropertyBag);

All these classes implement the interface iA.

I use reflection to create the relevant A... passing in a PropertyBag. I extract the data from the PropertyBag object to yield the candidate member data of the class.

What I want to be able to do though is to force an implementer of a class A... at compile time to implement a constructor of the above form. I am aware of the oddness of my request: why ever would you want to standardise construction parameters? But I have a case for it here.

Of course what I could do is to have a separate construction and initialisation step, as I could mark the initialisation function to be abstract, perhaps even changing iA to an abstract class containing that abstract initialisation function definition. I would use reflection to call initialise. That would give me the compile time failure as I desire if any A... is missing that initialise function. But I don't like the idea of separating construction and initialisation as an object that is constructed but not initialised has no meaning.

Am I missing a trick here? (In C++ I could enforce at compile time using templates, but can't see a way in Java).

like image 552
Bathsheba Avatar asked Dec 28 '25 03:12

Bathsheba


2 Answers

What I want to be able to do though is to force an implementer of a class A... at compile time to implement a constructor of the above form.

You can't, I'm afraid. There's just nothing within Java which would enforce that.

What you could do is write a unit test which finds all classes implementing the interface (e.g. by finding all classes in a jar file) and then checks that they have such a constructor. It's not as good as compile-time safety, but it's better than nothing.

like image 120
Jon Skeet Avatar answered Dec 30 '25 15:12

Jon Skeet


Despite what Jon says, there is a way to force a constructor.

Create an abstract class from the interface iA. In this abstract implementation you define the constructor you want and you make sure there is no default one.

Have all your classes extend the abstract implementation. They will be obliged to implement a constructor and call the super constructor (this is where you will put you initialization code).

There is a catch though. The implemented constructor can have any signature (except the default one).

Maybe this trick can help you.

like image 20
tom Avatar answered Dec 30 '25 17:12

tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!