Reputation: 13539
I have been doing Java for 12 years, and I have recently been doing Javascript, and I was wondering if the Java community has considered some kind of flexible constructor mechanism.
Things can get messy with constructors in Java. If there are many different pathways to create an object, then you need a constructor for each.
What if you could have a constructor where you can put in whatever values you like that would match up with a classes internal field :
Person p = new Person([
name:’bob’,
height:123,
address:new Address([
street:’asdf’,
postcode:4232
])
]);
(I am using square brackets here, but you would need some other symbol, as this would conflict with arrays in Java)
Then you define which fields in a class may be used in a constructor combination with an annotation :
public class Person{
@constructable
private String name;
@constructable
private int height;
@constructable
Private Address address;
.....
}
public class Address {
@constructable
private String street;
@constructable
private String postcode;
@constructable
private String city;
.....
}
This would all be syntactic sugar. During compile time, the compiler would work out all the constructors that are needed for a class and update the class accordingly.
Has anything like this ever been proposed a JSR?
Does this break any core philosophy behind Java? (Ie. Constructors should not be so unrestrictive)
Upvotes: 0
Views: 330
Reputation: 197
This can mostly be achieved by the Builder pattern. This is useful when there is a lot of information required to create the object.
Upvotes: 2