DecoratorUtils { @Nullable @SuppressWarnings("unchecked") public static <T> T getDecoratedEntity(final Object decoratedObject, final Class<T> clazz) { if (decoratedObject.getClass().isAssignableFrom(clazz)) { return (T) decoratedObject; } if (!(decoratedObject instanceof DecoratedObject)) { return null; } Object wrappedObject = ((DecoratedObject<T>) decoratedObject).getWrappedObject(); if (wrappedObject.getClass().isAssignableFrom(clazz)) { return (T) wrappedObject; } if (wrappedObject instanceof DecoratedObject) { return getDecoratedEntity(wrappedObject, clazz); } return null; } private  DecoratorUtils(); @Nullable @SuppressWarnings("unchecked") static T getDecoratedEntity(final Object decoratedObject, final Class<T> clazz);  }
@Test public void testGetDecoratedEntity() { DecoratorTest first = new DefaultDecoratorTest(); DecoratorTest second = new TestDecorator1(first); DecoratorTest third = new TestDecorator2(second); assertThat(getDecoratedEntity(first, DefaultDecoratorTest.class), notNullValue()); assertThat(getDecoratedEntity(first, TestDecorator1.class), nullValue()); assertThat(getDecoratedEntity(first, TestDecorator2.class), nullValue()); assertThat(getDecoratedEntity(second, DefaultDecoratorTest.class), notNullValue()); assertThat(getDecoratedEntity(second, TestDecorator1.class), notNullValue()); assertThat(getDecoratedEntity(second, TestDecorator1.class).specialMethod1(), equalTo("special1")); assertThat(getDecoratedEntity(second, TestDecorator2.class), nullValue()); assertThat(getDecoratedEntity(third, DefaultDecoratorTest.class), notNullValue()); assertThat(getDecoratedEntity(third, TestDecorator1.class), notNullValue()); assertThat(getDecoratedEntity(second, TestDecorator1.class).specialMethod1(), equalTo("special1")); assertThat(getDecoratedEntity(third, TestDecorator2.class), notNullValue()); assertThat(getDecoratedEntity(third, TestDecorator2.class).specialMethod2(), equalTo("special2")); }