diff --git a/src/main/java/org/fulib/yaml/IdMap.java b/src/main/java/org/fulib/yaml/IdMap.java index 08643d9..c4300ed 100644 --- a/src/main/java/org/fulib/yaml/IdMap.java +++ b/src/main/java/org/fulib/yaml/IdMap.java @@ -1,6 +1,5 @@ package org.fulib.yaml; -import java.lang.reflect.Method; import java.util.Collection; import java.util.LinkedHashMap; @@ -199,26 +198,28 @@ private String generateUniqueKey(Object obj) return yamlObj.getId(); } - String key = getIntrinsicKey(obj); - key = StrUtil.downFirstChar(key); + String key = this.getIntrinsicKey(obj); + key = key.replaceAll("\\W+", "_"); + key = key.isEmpty() ? "_" : StrUtil.downFirstChar(key); key = this.makeUnique(key); key = this.addUserId(key); return key; } - private static String getIntrinsicKey(Object obj) + private String getIntrinsicKey(Object obj) { - final Class clazz = obj.getClass(); - final String id = getKeyFromProperty(obj, clazz, "getId"); + final Reflector reflector = this.getReflector(obj); + + final Object id = reflector.getValue(obj, "id"); if (id != null) { - return id; + return id.toString(); } - final String name = getKeyFromProperty(obj, clazz, "getName"); + final Object name = reflector.getValue(obj, "name"); if (name != null) { - return name; + return name.toString(); } return obj.getClass().getSimpleName().substring(0, 1); @@ -244,22 +245,4 @@ private String addUserId(String key) } return key; } - - private static String getKeyFromProperty(Object obj, Class clazz, String getterName) - { - try - { - Method getter = clazz.getMethod(getterName); - Object result = getter.invoke(obj); - if (result != null) - { - return result.toString().replaceAll("\\W+", "_"); - } - } - catch (Exception ignored) - { - // go with old key - } - return null; - } } diff --git a/src/test/java/org/fulib/yaml/TestYamlIdMap.java b/src/test/java/org/fulib/yaml/TestYamlIdMap.java index af0b22a..ed13b6c 100644 --- a/src/test/java/org/fulib/yaml/TestYamlIdMap.java +++ b/src/test/java/org/fulib/yaml/TestYamlIdMap.java @@ -104,14 +104,23 @@ public void testUserObjectIds() Room arts = new Room().setId("arts"); Room other = new Room().setId("other"); Room other2 = new Room().setId("other"); + Room empty = new Room().setId(""); + Room empty2 = new Room().setId(""); - uni.withRooms(math).withRooms(arts).withRooms(other).withRooms(other2); + uni.withRooms(math); + uni.withRooms(arts); + uni.withRooms(other); + uni.withRooms(other2); + uni.withRooms(empty); + uni.withRooms(empty2); YamlIdMap idMap = new YamlIdMap(uni.getClass().getPackage().getName()); - String encode = idMap.encode(uni); + idMap.encode(uni); assertThat(idMap.getId(math), is("math")); assertThat(idMap.getId(other), is("other")); assertThat(idMap.getId(other2), is("other1")); + assertThat(idMap.getId(empty), is("_")); + assertThat(idMap.getId(empty2), is("_2")); } @Test