Guaranteeing type safety in ConfigurationSerializable Lists

Discussion in 'Plugin Development' started by 1Rogue, Feb 3, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    1Rogue

    Attempting to write a #getXList() method for my configuration wrapper, however I'm not certain about guaranteeing the list type on a returned value. I want to make sure that if there's one "bad apple" in the list, it wouldn't reject the entire list:

    Code:java
    1. public synchronized List<CuboidRegion> getCuboidRegionList(ConfigValues path) {
    2. List<?> result = this.yaml.getList(path.getPath());
    3.  
    4. if (result == null) {
    5. return new ArrayList<>(0);
    6. }
    7.  
    8. List<CuboidRegion> back = new ArrayList<>();
    9.  
    10. for (Object obj : result) {
    11. if (obj instanceof Map) {
    12. back.add(PWCuboidRegion.deserialize((Map) obj));
    13. }
    14. }
    15. return back;
    16. }


    Where "this.yaml" is a YamlConfiguration file (ConfigValues is just an enum with self-explanatory methods).

    Does anyone have a "type safe" version of getting a custom ConfigurationSerializable list?
     
  2. Offline

    xTrollxDudex

    1Rogue
    Instanceof checks?
     
  3. Offline

    RawCode

    standart YML implementation will throw exception and cease future operations on any invalid entry.
    you must handle YML differently - read file youself or read entries line by line catching possible exceptions in process.

    checking instance is dead end, if object may not "fit" some format it will fail at instantiation stage and wont get into list at all.
     
  4. Offline

    1Rogue


    I already check the instance


    The idea is that I'm somewhat avoiding that by getting a raw list, and then attempting a cast before loading the object (code is outdated a bit, looks like this currently):

    Code:java
    1. for (Object obj : result) {
    2. if (obj instanceof Map) {
    3. try {
    4. PWCuboidRegion cr = PWCuboidRegion.valueOf((Map) obj);
    5. back.add(cr);
    6. } catch (Exception e) {} // Failed objects shouldn't load
    7. }
    8. }
     
  5. Offline

    RawCode

    How it works:

    1) You read from file
    2) YML somewhere construct Map objects (via new instance or other way it does not matter)
    3) if object does not fit new instance will fail
    4) if YML malformed - read will fail

    your code will never hit instanceof check
     
  6. Offline

    1Rogue


    Right, but those are stored as objects. Custom ConfigurationSerializable classes are still simply made up of Map<String, Object>, however recursive. It wouldn't fail until a cast/deserialize
     
  7. Offline

    RawCode

    only possible situation to hit instanceof check in your current code is to manually add some random object into list, in all other cases if something can fail, it will fail before loop.
     
Thread Status:
Not open for further replies.

Share This Page