Create custom objects on the fly
I would like to know if there is a way to create objects on the fly or should I say without using the Class object and its properties. The usual way I go about doing this is this.
ApiHelper apiHelper = new ApiHelper();
User user = new User();
user.Firstname = "FirstName";
apiHelper.send("", user);
I would like to accomplish this in my code snippet:
ApiHelper apiHelper = new ApiHelper();
apiHelper.send("", new { Firstname = "Firstname"});
The second parameter to send () is of the Object data type, and this object is later converted to a json string.
This is a C # example, are there any analogues in Java? I think if I use the first approach when creating objects, I must have many classes to match the objects I need to assemble, so I was hoping I could do it in java using the 2nd approach.
This may be a strange or strange question for some, so please with me. I have still been using C # for a long time. Any ideas? Thank!
source to share
This is technically possible with Java. the syntax will be as follows:
apiHelper.send("", new Object(){ String firstName = "Firstname"});
However, this is generally pretty useless. What you most likely want to do is create an interface / class to define the methods and fields you want and pass an instance to them.
Example:
class Data{
String firstname;
public Data(String firstname){
this.firstname=firstname;
}
}
source to share
Well, all you really need is a constructor that takes Firstname
as a parameter.
public User(String fName) {
Firstname = fName;
}
Although, capitalizing your members is not a Java convention as it is in C #; should be
String firstname;
Then you just do ...
apiHelper.send("", new User("Firstname"));
source to share
If you cannot change User
to add a constructor, then I would use "double-bound initialization" where you can basically run the code in the class in which this instance is instantiated:
ApiHelper apiHelper = new ApiHelper();
apiHelper.send("", new User(){{
Firstname = "Firstname";
}});
Then the line Firstname = "Firstname";
is executed right after the instance.
source to share