简体   繁体   English

如何在Java中为类创建动态对象?

[英]How to create dynamic object for class in java?

Ex: 例如:

Element elementInclude1 = doc.createElement("include");
elementMethods.appendChild(elementInclude1);
elementInclude1.setAttribute("name", "T1");

Element elementInclude2 = doc.createElement("include");
elementMethods.appendChild(elementInclude2);
elementInclude2.setAttribute("name", "T2");

Element elementInclude3 = doc.createElement("include");
elementMethods.appendChild(elementInclude3);
elementInclude3.setAttribute("name", "T3");
....

In the above example, number of objects(elementInclude1, elementInclude2,..) created are known dynamically. 在上面的示例中,创建的对象(elementInclude1,elementInclude2,..)的数量是动态已知的。

No of object required are known in run time, using that value iterating in the loop new object created in each iteration. 在运行时不知道需要的对象,使用该值在循环中迭代每次迭代中创建的新对象。 how can I achieve that. 我该如何实现。

Need to create objects elementInclude1, elementInclude2, elementInclude3,... dynamically while run time 需要在运行时动态创建对象elementInclude1,elementInclude2,elementInclude3,...

Just for better understanding I used some wrong practice in the below code. 为了更好地理解,我在以下代码中使用了一些错误的做法。

String noOfObj = 5;
for(int i = 1; i<=noOfObj; i++)
{
Element elementInclude+**noOfObj** = doc.createElement("include");
elementMethods.appendChild(elementInclude+**noOfObj**);
elementInclude+**noOfObj**.setAttribute("name", "T1");
}
    int noOfObj = 5;
    //create an array to hold elements
    Element[] elememtsArray = new Element[noOfObj];

    for(int i = 1; i<=noOfObj ; i++){

        Element element = doc.createElement("include");
        elememtsArray[i] = element;
    }

Alternatively, if the number of elements is un known, use list 或者,如果元素数量未知,请使用列表

    ArrayList<Element> elementsList = new ArrayList<>();

    for(int i = 1; i<= 6 ; i++){//6 is an arbitrary num for demo

        Element element = doc.createElement("include");
         elementsList.add(element);
    }

Alternatively, if you need the reference name, use map 或者,如果您需要参考名称,请使用map

    Map<String, Element> elementsMap= new HashMap();
    for(int i = 1; i<=7 ; i++){ //7 is an arbitrary num for demo

        Element element = doc.createElement("include");
        String elementName = "elementInclude"+ i;
        elementsMap.put(elementName, element);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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