Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom objects on the fly

Tags:

java

object

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.

like image 564
Luke Villanueva Avatar asked Aug 05 '14 19:08

Luke Villanueva


3 Answers

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;
    }
}
like image 192
resueman Avatar answered Sep 28 '22 01:09

resueman


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"));

like image 31
ChiefTwoPencils Avatar answered Sep 28 '22 02:09

ChiefTwoPencils


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.

like image 41
The Guy with The Hat Avatar answered Sep 28 '22 02:09

The Guy with The Hat