Best way to call dynamic title from View class?

From the Vaadin start I made a project a while back, which uses the @PageTitle annotation, which is fine. However I want to create a page with a dynamic title.

I implemented HasDynamicTitle however the default logic in the MainLayout class uses reflection to get the PageTitle annotation.

So I modified the logic to call the getPageTitle() method I implemented. However is there a better/safer way than this?


    private String getCurrentPageTitle() {
        PageTitle title = getContent().getClass().getAnnotation(PageTitle.class);

        if (Objects.isNull(title)) {
            try {
                getContent().getClass().getMethod("getPageTitle");
            } catch (NoSuchMethodException e) {
                return "";
            }
        }
        return title.value();
    }

What about?

private String getCurrentPageTitle() { PageTitle title = getContent().getClass() .getAnnotation(PageTitle.class); String titleString = ""; if (Objects.isNull(title)) { if (getContent() instanceof HasDynamicTitle component) { titleString = component.getPageTitle(); } } return title == null ? titleString : title.value(); }