简体   繁体   中英

Java set values of list of custom object which is a inner class

Hi I am facing a problem while trying to set a list of custom class object which is inside another class.

public class Request {

  private List<Custom> Custom;

  public List<Request.Custom> getCustom() {
    return Custom;
  }

  public void setCustom(List<Request.Custom> custom) {
    Custom= custom;
  }

public class Custom{

    private String id;

    public String getid() {
        return id;
    }

    public void setid(String Id) {
        id= Id;
    }
  }
}

Now how do I set the id from another class?

Use following syntax to create object of inner class :

classInstance.new InnerClass()

Then you can have a list of Custom from other class

Request req = new Request();
List<Request.Custom> clist = new ArrayList<>();
Request.Custom c;

c = req.new Custom();
c.setid("one");
clist.add(c);

c = req.new Custom();
c.setid("two");
clist.add(c);

req.setCustom(clist);

You have to do it so:

Request myR = new Request( );
Request.Custom myCustom = myR.new Custom();
myCustom.setid("17");

the trick here is myR.new Custom(); and this is the consequence because you are using inner/nested classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM