<T extends Composite> T parse(String stringText, Class<T> compositeClass) throws ParsingException, IllegalAccessException, InstantiationException { T type; try { type = compositeClass.newInstance(); Class componentClass = componentMap.get(compositeClass); Matcher matcher = patterns.get(componentClass).matcher(stringText); while (matcher.find()) { if (componentClass == SentenceToken.class) { if (matcher.group().matches(patterns.get(Word.class).toString())) { type.add(new Word(matcher.group())); } if (matcher.group().matches(patterns.get(Numbers.class).toString())) { Numbers number = new Numbers(); number.add(new Integer(matcher.group())); type.add(number); } if (matcher.group().matches(patterns.get(Punctuation.class).toString())) { Punctuation punctuation = new Punctuation(); punctuation.add(matcher.group().charAt(0)); type.add(punctuation); } if (matcher.group().matches(patterns.get(Space.class).toString())) { Space space = new Space(); space.add(matcher.group().charAt(0)); type.add(space); } } else { Component c = parse(matcher.group(), componentClass); type.add(c); } } return type; } catch (InstantiationException | IllegalAccessException ignored) { logger.error("Could not parse the elements of text "); throw new ParsingException("Could not parse the elements of text "); } }