How to define a java object name with a variable?

前端 未结 3 1608
鱼传尺愫
鱼传尺愫 2020-11-30 06:40

I need to create a large number of objects using a pattern of naming easily obtainable through a loop. Is there any way to have an object name be read from a variable, like

3条回答
  •  自闭症患者
    2020-11-30 06:45

    It's not at all clear what you want. If you want to look up objects by name, you could use a Map

    Example:

    Map map = new HashMap();
    
    String objectName = ...// get name of object
    Object object = ...// get object
    map.put(objectName, object);
    

    Then it can be retrieved:

    Object obj = map.get(objectName);
    

提交回复
热议问题