Ankit Pise Ankit Pise - 11 months ago 59
Java Question

Passing POJO class, object to another POJO

I am sure this question might have been asked couple of times here but I am not understanding what query I should use.
What I want to do is, Passing POJO to another POJO where parameter could be dynamic

like example below

Class DataPOJO{
private String name;
public String getName(){
public void setName(String name){

I want to make another POJO where I can pass value like

RequestmakerPOJO request = new RequestmakerPOJO(authorisationObject, dataPOJO, DataPOJO);

Where dataPOJO would be object I created and DataPOJO.class it's structure, later I can pass any kind of pojo to this new Requestmaker class with it's structure definition and object just like.
HashMap<ObjectType, ObjectType2>

But I want only 1 Object type to be passed and then it's object. I am new at java so I don't know what to call these scenarios. Please help me out with the query or solution.

:) thanks

Answer Source

You should declare RequestmakerPOJO as a generic class:

class RequestmakerPOJO<T> {

Now you can use T as a type wherever you want. For example, the constructor can be

RequestmakerPOJO(AuthPOJO auth, T data) {

To declare a variable

RequestmakerPOJO<DataPOJO> request = new RequestmakerPOJO<>(auth, data);

For more details, research generics in Java.