DeclarableTypeInstantiator { public static <T extends Declarable> T newInstance(DeclarableType declarableType, Cache cache) { try { Class<T> loadedClass = (Class<T>) ClassPathLoader.getLatest().forName(declarableType.getClassName()); T declarable = loadedClass.newInstance(); Properties initProperties = new Properties(); for (ParameterType parameter : declarableType.getParameters()) { initProperties.put(parameter.getName(), newInstance(parameter, cache)); } declarable.initialize(cache, initProperties); return declarable; } catch (Exception e) { throw new RuntimeException( "Error instantiating class: <" + declarableType.getClassName() + ">", e); } }  static T newInstance(DeclarableType declarableType, Cache cache); static T newInstance(ObjectType objectType, Cache cache); static V newInstance(ClassName type, Cache cache); static V newInstance(ClassNameType className);  }
@Test public void createDeclarableInstanceFromDeclarableType() { DeclarableType declarableType = new DeclarableType(MyDeclarable.class.getName(), "{\"value1\":5,\"value2\":\"some string\"}"); MyDeclarable result = DeclarableTypeInstantiator.newInstance(declarableType, cache); assertThat(result).isNotNull().isInstanceOf(MyDeclarable.class); assertThat(result.props).isNotNull(); assertThat(result.props.getProperty("value1")).isEqualTo("5"); assertThat(result.props.getProperty("value2")).isEqualTo("some string"); }
@Test public void createDeclarableInstancedFromNestedDeclarableType() { DeclarableType declarableType = new DeclarableType(MyDeclarable.class.getName(), "{\"value1\":5,\"value2\":\"some string\"}"); ParameterType parameterType = new ParameterType("inner-prop", declarableType); DeclarableType outerDeclarable = new DeclarableType(MyOuterDeclarable.class.getName()); outerDeclarable.getParameters().add(parameterType); MyOuterDeclarable result = DeclarableTypeInstantiator.newInstance(outerDeclarable, cache); assertThat(result.props).isNotNull(); MyDeclarable innerDeclarable = (MyDeclarable) result.props.get("inner-prop"); assertThat(innerDeclarable.props.getProperty("value1")).isEqualTo("5"); assertThat(innerDeclarable.props.getProperty("value2")).isEqualTo("some string"); }
@Test public void getInstance() { ClassName klass = new ClassName("java.lang.String"); String s = DeclarableTypeInstantiator.newInstance(klass, null); assertThat(s).isEqualTo(""); }
@Test public void getInstanceWithProps() { String json = "{\"k\":\"v\"}"; ClassName cacheWriter = new ClassName(MyCacheWriter.class.getName(), json); MyCacheWriter obj = DeclarableTypeInstantiator.newInstance(cacheWriter, null); assertThat(obj.getProperties()).containsEntry("k", "v").containsOnlyKeys("k"); }
@Test public void emptyCanNotInstantiate() { assertThatThrownBy(() -> DeclarableTypeInstantiator.newInstance(ClassName.EMPTY, null)) .isInstanceOf(RuntimeException.class) .hasMessageContaining("Error instantiating class"); }