Reputation: 450
In my program; I have an object which stores name, description, languages that he/she speaks, when created, address, reputation. But the must have fields are name, description, languages and the others are non compulsory. I don't want to write two methods and let user select one and the make other fields null according to usage, such as;
inside of constructor(name, description, languages) {
this.name = name;
this.description = description;
this.languages = languages;
this.address = " ";
this.reputation = " ";
}
inside of constructor(name, description, languages, address, reputation) {
this.name = name;
this.description = description;
this.languages = languages;
this.address = address;
this.reputation = reputation;
}
So how can I solve this problem? Is there a way I can create fields according fields that user provides?
I am using java.
Thanks in advance.
Upvotes: 2
Views: 118
Reputation: 158
Have a look at the following URL which explains Builder Pattern.
https://stackoverflow.com/a/1953567/705315
~HTH
PS : Unable to comment on your question. Hence posting as answer.
Upvotes: 1
Reputation: 1474
The java compiler API allows you to invoke the Java compiler with source code that you can specify at runtime in another java program. Probably not what you are looking for, but it is possible to create a class with fields the user specifies at runtime to answer your question. I can provide an example if you want.
Upvotes: 0
Reputation: 1889
You can make a constructor with a variable number of arguments:
public class VarArg {
public VarArg(String ... args)
{
String a = args[0];
String b = args[1];
}
public static void main(String[] args)
{
VarArg arg1 = new VarArg("hello");
VarArg arg2 = new VarArg("hello","goodbye");
}
}
But I would probably use a Map with named keys as the parameter to your constructor (as suggested by mauhiz above).
Upvotes: 0
Reputation: 315
A better option would be to provide getter setter methods for the variables, so that the user can call only those methods that set values for mandatory fields. So try creating a Bean class mapping to the form, with fields mapping to the variables.
Upvotes: 1
Reputation: 501
There is no "default value" for parameters in Java, so you would have to provide 2 constructors (one can be calling the other though).
If your fields are quite dynamic, what about using a Map<String, String> as a single parameter? This is usually not a pretty pattern but it could fit your use case.
Upvotes: 0
Reputation: 533660
To have a different set of fields you need a different class. You could generate a class for every combination if you wish using a factory or builder to do this (I have done this before and its not simple ;) but I would create a one class which has all possible fields and use that.
Upvotes: 0