I would like to know if there's a way to create objects on the fly or should I say by not using a Class object and its properties. The normal way I'm doing it is this.
ApiHelper apiHelper = new ApiHelper();
User user = new User();
user.Firstname = "FirstName";
apiHelper.send("", user);
I would like to accomplish this on my code snippet:
ApiHelper apiHelper = new ApiHelper();
apiHelper.send("", new { Firstname = "Firstname"});
The second paramter on send() has a data type of Object and this Object is later on converted to json string.
This is a c# example, is there a counterpart of this in java? I kind of think that if I use the first approach when creating objects, I have to a lot of classes just to comply with the objects that I need to build, So I was hoping to if I can do it in java using the 2nd approach.
Technically, that's possible with Java. the syntax would be this:
apiHelper.send("", new Object(){ String firstName = "Firstname"});
However, that's generally pretty useless. What you more likely want to do it create an interface/class to define the methods and fields you want, and pass an instance of that.
Example:
class Data{
String firstname;
public Data(String firstname){
this.firstname=firstname;
}
}
Well, all you really need is a constructor that takes the Firstname
as a parameter.
public User(String fName) {
Firstname = fName;
}
Although, capitalizing your members isn't convention in Java as it is in C#; should be
String firstname;
Then you would just do...
apiHelper.send("", new User("Firstname"));
If you can't modify User
to add a constructor, what I would use is "double brace initialization," where you can basically run code in a class where that class is instantiated:
ApiHelper apiHelper = new ApiHelper();
apiHelper.send("", new User(){{
Firstname = "Firstname";
}});
Then the line Firstname = "Firstname";
gets executed immediately after instantiation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With