All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hibernate.search.engine.environment.bean.CastingBeanReference Maven / Gradle / Ivy

The newest version!
/*
 * SPDX-License-Identifier: Apache-2.0
 * Copyright Red Hat Inc. and Hibernate Authors
 */
package org.hibernate.search.engine.environment.bean;

import org.hibernate.search.util.common.impl.SuppressingCloser;

final class CastingBeanReference implements BeanReference {
	private final BeanReference casted;
	private final Class expectedType;

	CastingBeanReference(BeanReference casted, Class expectedType) {
		this.casted = casted;
		this.expectedType = expectedType;
	}

	@Override
	@SuppressWarnings("unchecked") // Checked using reflection
	public BeanHolder resolve(BeanResolver beanResolver) {
		BeanHolder beanHolder = casted.resolve( beanResolver );
		try {
			// Just let the type throw an exception if something is wrong
			expectedType.cast( beanHolder.get() );
			// The instance can safely be cast to the expected type, so we can safely do this
			return (BeanHolder) beanHolder;
		}
		catch (Exception e) {
			new SuppressingCloser( e ).push( beanHolder );
			throw e;
		}
	}

	@Override
	@SuppressWarnings("unchecked") // Checked using reflection
	public  BeanReference asSubTypeOf(Class expectedType2) {
		if ( expectedType2.isAssignableFrom( expectedType ) ) {
			return (BeanReference) this;
		}
		else {
			return casted.asSubTypeOf( expectedType2 );
		}
	}
}