下面列出了怎么用org.hibernate.internal.util.ReflectHelper的API类实例代码及写法,或者点击链接到github查看源代码。
private void checkCompositeIdentifier() {
if ( getIdentifier() instanceof Component ) {
Component id = (Component) getIdentifier();
if ( !id.isDynamic() ) {
final Class idClass = id.getComponentClass();
if ( idClass != null ) {
final String idComponentClassName = idClass.getName();
if ( !ReflectHelper.overridesEquals( idClass ) ) {
LOG.compositeIdClassDoesNotOverrideEquals( idComponentClassName );
}
if ( !ReflectHelper.overridesHashCode( idClass ) ) {
LOG.compositeIdClassDoesNotOverrideHashCode( idComponentClassName );
}
if ( !Serializable.class.isAssignableFrom( idClass ) ) {
throw new MappingException(
"Composite-id class must implement Serializable: " + idComponentClassName
);
}
}
}
}
}
/**
* Used by JDK serialization...
*
* @param ois The input stream from which we are being read...
* @throws java.io.IOException Indicates a general IO stream exception
* @throws ClassNotFoundException Indicates a class resolution issue
*/
protected void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
final String memberDeclaringClassName = ( String ) ois.readObject();
final String memberName = ( String ) ois.readObject();
final String memberType = ( String ) ois.readObject();
final Class memberDeclaringClass = Class.forName(
memberDeclaringClassName,
false,
declaringType.getJavaType().getClassLoader()
);
try {
this.member = "method".equals( memberType )
? memberDeclaringClass.getMethod( memberName, ReflectHelper.NO_PARAM_SIGNATURE )
: memberDeclaringClass.getField( memberName );
}
catch ( Exception e ) {
throw new IllegalStateException(
"Unable to locate member [" + memberDeclaringClassName + "#"
+ memberName + "]"
);
}
}
private Constructor<? extends EntityTuplizer> getProperConstructor(
Class<? extends EntityTuplizer> clazz,
Class[] constructorArgs) {
Constructor<? extends EntityTuplizer> constructor = null;
try {
constructor = clazz.getDeclaredConstructor( constructorArgs );
try {
ReflectHelper.ensureAccessibility( constructor );
}
catch ( SecurityException e ) {
constructor = null;
}
}
catch ( NoSuchMethodException ignore ) {
}
return constructor;
}
public PojoInstantiator(
Class mappedClass,
ReflectionOptimizer.InstantiationOptimizer optimizer,
boolean embeddedIdentifier) {
this.mappedClass = mappedClass;
this.optimizer = optimizer;
this.embeddedIdentifier = embeddedIdentifier;
this.isAbstract = ReflectHelper.isAbstractClass( mappedClass );
try {
constructor = ReflectHelper.getDefaultConstructor(mappedClass);
}
catch ( PropertyNotFoundException pnfe ) {
LOG.noDefaultConstructor( mappedClass.getName() );
constructor = null;
}
}
@SuppressWarnings("unchecked")
private Constructor<? extends ComponentTuplizer> getProperConstructor(Class<? extends ComponentTuplizer> clazz) {
Constructor<? extends ComponentTuplizer> constructor = null;
try {
constructor = clazz.getDeclaredConstructor( COMPONENT_TUP_CTOR_SIG );
try {
ReflectHelper.ensureAccessibility( constructor );
}
catch ( SecurityException e ) {
constructor = null;
}
}
catch ( NoSuchMethodException ignore ) {
}
return constructor;
}
@Override
public void postInstantiate(
final String entityName,
final Class persistentClass,
final Set<Class> interfaces,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
CompositeType componentIdType) throws HibernateException {
this.entityName = entityName;
this.persistentClass = persistentClass;
this.interfaces = toArray( interfaces );
this.getIdentifierMethod = getIdentifierMethod;
this.setIdentifierMethod = setIdentifierMethod;
this.componentIdType = componentIdType;
this.overridesEquals = ReflectHelper.overridesEquals( persistentClass );
this.proxyClass = buildJavassistProxyFactory().createClass();
}
@Override
public void postInstantiate(
String entityName,
Class persistentClass,
Set<Class> interfaces,
Method getIdentifierMethod,
Method setIdentifierMethod,
CompositeType componentIdType) throws HibernateException {
this.entityName = entityName;
this.persistentClass = persistentClass;
this.interfaces = toArray( interfaces );
this.getIdentifierMethod = getIdentifierMethod;
this.setIdentifierMethod = setIdentifierMethod;
this.componentIdType = componentIdType;
this.overridesEquals = ReflectHelper.overridesEquals( persistentClass );
this.proxyClass = byteBuddyProxyHelper.buildProxy( persistentClass, this.interfaces );
}
private Class locateOracleTypesClass() {
try {
return ReflectHelper.classForName( ORACLE_TYPES_CLASS_NAME );
}
catch (ClassNotFoundException e) {
try {
return ReflectHelper.classForName( DEPRECATED_ORACLE_TYPES_CLASS_NAME );
}
catch (ClassNotFoundException e2) {
throw new HibernateException(
String.format(
"Unable to locate OracleTypes class using either known FQN [%s, %s]",
ORACLE_TYPES_CLASS_NAME,
DEPRECATED_ORACLE_TYPES_CLASS_NAME
),
e
);
}
}
}
public void lookupConstant(DotNode node) throws SemanticException {
String text = ASTUtil.getPathText( node );
Queryable persister = walker.getSessionFactoryHelper().findQueryableUsingImports( text );
if ( persister != null ) {
// the name of an entity class
final String discrim = persister.getDiscriminatorSQLValue();
node.setDataType( persister.getDiscriminatorType() );
if ( InFragment.NULL.equals( discrim ) || InFragment.NOT_NULL.equals( discrim ) ) {
throw new InvalidPathException(
"subclass test not allowed for null or not null discriminator: '" + text + "'"
);
}
// the class discriminator value
setSQLValue( node, text, discrim );
}
else {
Object value = ReflectHelper.getConstantValue( text, walker.getSessionFactoryHelper().getFactory() );
if ( value == null ) {
throw new InvalidPathException( "Invalid path: '" + text + "'" );
}
setConstantValue( node, text, value );
}
}
public CollectionType customCollection(
String typeName,
Properties typeParameters,
String role,
String propertyRef) {
Class typeClass;
try {
typeClass = ReflectHelper.classForName( typeName );
}
catch (ClassNotFoundException cnfe) {
throw new MappingException( "user collection type class not found: " + typeName, cnfe );
}
CustomCollectionType result = new CustomCollectionType( typeScope, typeClass, role, propertyRef );
if ( typeParameters != null ) {
injectParameters( result.getUserType(), typeParameters );
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public void setParameterValues(Properties parameters) {
ParameterType reader = (ParameterType) parameters.get( PARAMETER_TYPE );
if ( reader != null ) {
setJavaTypeDescriptor( new SerializableTypeDescriptor<T>( reader.getReturnedClass() ) );
}
else {
String className = parameters.getProperty( CLASS_NAME );
if ( className == null ) {
throw new MappingException( "No class name defined for type: " + SerializableToBlobType.class.getName() );
}
try {
setJavaTypeDescriptor( new SerializableTypeDescriptor<T>( ReflectHelper.classForName( className ) ) );
}
catch ( ClassNotFoundException e ) {
throw new MappingException( "Unable to load class from " + CLASS_NAME + " parameter", e );
}
}
}
public static ProxyDefinitions createFromMetadata(Metadata storeableMetadata, PreGeneratedProxies preGeneratedProxies) {
//Check upfront for any need across all metadata: would be nice to avoid initializing the Bytecode provider.
LazyBytecode lazyBytecode = new LazyBytecode();
if (needAnyProxyDefinitions(storeableMetadata)) {
final HashMap<Class<?>, ProxyClassDetailsHolder> proxyDefinitionMap = new HashMap<>();
try {
for (PersistentClass persistentClass : storeableMetadata.getEntityBindings()) {
if (needsProxyGeneration(persistentClass)) {
final Class mappedClass = persistentClass.getMappedClass();
final Class proxyClassDefinition = generateProxyClass(persistentClass, lazyBytecode,
preGeneratedProxies);
if (proxyClassDefinition == null) {
continue;
}
final boolean overridesEquals = ReflectHelper.overridesEquals(mappedClass);
try {
proxyDefinitionMap.put(mappedClass,
new ProxyClassDetailsHolder(overridesEquals, proxyClassDefinition.getConstructor()));
} catch (NoSuchMethodException e) {
throw new HibernateException(
"Failed to generate Enhanced Proxy: default constructor is missing for entity '"
+ mappedClass.getName() + "'. Please add a default constructor explicitly.");
}
}
}
} finally {
lazyBytecode.close();
}
return new ProxyDefinitions(proxyDefinitionMap);
} else {
return new ProxyDefinitions(Collections.emptyMap());
}
}
@Override
public void setTypeUsingReflection(String className, String propertyName) throws MappingException {
if (referencedEntityName == null) {
final ClassLoaderService cls = getMetadata().getMetadataBuildingOptions()
.getServiceRegistry()
.getService( ClassLoaderService.class );
referencedEntityName = ReflectHelper.reflectedPropertyClass( className, propertyName, cls ).getName();
}
}
@Override
public void setTypeUsingReflection(String className, String propertyName) throws MappingException {
// NOTE : this is called as the last piece in setting SimpleValue type information, and implementations
// rely on that fact, using it as a signal that all information it is going to get is defined at this point...
if ( typeName != null ) {
// assume either (a) explicit type was specified or (b) determine was already performed
return;
}
if ( type != null ) {
return;
}
if ( attributeConverterDescriptor == null ) {
// this is here to work like legacy. This should change when we integrate with metamodel to
// look for SqlTypeDescriptor and JavaTypeDescriptor individually and create the BasicType (well, really
// keep a registry of [SqlTypeDescriptor,JavaTypeDescriptor] -> BasicType...)
if ( className == null ) {
throw new MappingException( "Attribute types for a dynamic entity must be explicitly specified: " + propertyName );
}
typeName = ReflectHelper.reflectedPropertyClass(
className,
propertyName,
getMetadata()
.getMetadataBuildingOptions()
.getServiceRegistry()
.getService( ClassLoaderService.class )
).getName();
// todo : to fully support isNationalized here we need do the process hinted at above
// essentially, much of the logic from #buildAttributeConverterTypeAdapter wrt resolving
// a (1) SqlTypeDescriptor, a (2) JavaTypeDescriptor and dynamically building a BasicType
// combining them.
return;
}
// we had an AttributeConverter...
type = buildAttributeConverterTypeAdapter();
}
@SuppressWarnings("unchecked")
private Method resolveMethod() {
try {
final Method method = declaringClass.getDeclaredMethod( methodName, argumentType );
ReflectHelper.ensureAccessibility( method );
return method;
}
catch (NoSuchMethodException e) {
throw new PropertyAccessSerializationException(
"Unable to resolve setter method on deserialization : " + declaringClass.getName() + "#"
+ methodName + "(" + argumentType.getName() + ")"
);
}
}
public GetterFieldImpl(Class containerClass, String propertyName, Field field) {
this.containerClass = containerClass;
this.propertyName = propertyName;
this.field = field;
this.getterMethod = ReflectHelper.findGetterMethodForFieldAccess( field, propertyName );
}
@SuppressWarnings("unchecked")
private Method resolveMethod() {
try {
final Method method = declaringClass.getDeclaredMethod( methodName );
ReflectHelper.ensureAccessibility( method );
return method;
}
catch (NoSuchMethodException e) {
throw new PropertyAccessSerializationException(
"Unable to resolve getter method on deserialization : " + declaringClass.getName() + "#" + methodName
);
}
}
protected static Field fieldOrNull(Class containerJavaType, String propertyName) {
try {
return ReflectHelper.findField( containerJavaType, propertyName );
}
catch (PropertyNotFoundException e) {
return null;
}
}
public PropertyAccessFieldImpl(
PropertyAccessStrategyFieldImpl strategy,
Class containerJavaType,
final String propertyName) {
this.strategy = strategy;
final Field field = ReflectHelper.findField( containerJavaType, propertyName );
this.getter = new GetterFieldImpl( containerJavaType, propertyName, field );
this.setter = new SetterFieldImpl( containerJavaType, propertyName, field );
}
protected Field resolveField() {
try {
final Field field = declaringClass.getDeclaredField( fieldName );
ReflectHelper.ensureAccessibility( field );
return field;
}
catch (NoSuchFieldException e) {
throw new PropertyAccessSerializationException(
"Unable to resolve field on deserialization : " + declaringClass.getName() + "#" + fieldName
);
}
}
public PropertyAccessBasicImpl(
PropertyAccessStrategyBasicImpl strategy,
Class containerJavaType,
final String propertyName) {
this.strategy = strategy;
final Method getterMethod = ReflectHelper.findGetterMethod( containerJavaType, propertyName );
this.getter = new GetterMethodImpl( containerJavaType, propertyName, getterMethod );
final Method setterMethod = ReflectHelper.findSetterMethod( containerJavaType, propertyName, getterMethod.getReturnType() );
this.setter = new SetterMethodImpl( containerJavaType, propertyName, setterMethod );
}
/**
* Construct an instance of the given tuplizer class.
*
* @param tuplizerClassName The name of the tuplizer class to instantiate
* @param metamodel The metadata for the entity.
* @param persistentClass The mapping info for the entity.
*
* @return The instantiated tuplizer
*
* @throws HibernateException If class name cannot be resolved to a class reference, or if the
* {@link Constructor#newInstance} call fails.
*/
@SuppressWarnings({ "unchecked" })
public EntityTuplizer constructTuplizer(
String tuplizerClassName,
EntityMetamodel metamodel,
PersistentClass persistentClass) {
try {
Class<? extends EntityTuplizer> tuplizerClass = ReflectHelper.classForName( tuplizerClassName );
return constructTuplizer( tuplizerClass, metamodel, persistentClass );
}
catch ( ClassNotFoundException e ) {
throw new HibernateException( "Could not locate specified tuplizer class [" + tuplizerClassName + "]" );
}
}
public PojoInstantiator(Class componentClass, ReflectionOptimizer.InstantiationOptimizer optimizer) {
this.mappedClass = componentClass;
this.isAbstract = ReflectHelper.isAbstractClass( mappedClass );
this.optimizer = optimizer;
this.embeddedIdentifier = false;
try {
constructor = ReflectHelper.getDefaultConstructor(mappedClass);
}
catch ( PropertyNotFoundException pnfe ) {
LOG.noDefaultConstructor(mappedClass.getName());
constructor = null;
}
}
protected Instantiator buildInstantiator(Component component) {
if ( component.isEmbedded() && ReflectHelper.isAbstractClass( this.componentClass ) ) {
return new ProxiedInstantiator( this.componentClass );
}
if ( optimizer == null ) {
return new PojoInstantiator( this.componentClass, null );
}
else {
return new PojoInstantiator( this.componentClass, optimizer.getInstantiationOptimizer() );
}
}
private static Constructor getConstructor(PersistentClass persistentClass) {
if ( persistentClass == null || !persistentClass.hasPojoRepresentation() ) {
return null;
}
try {
return ReflectHelper.getDefaultConstructor( persistentClass.getMappedClass() );
}
catch (Throwable t) {
return null;
}
}
public FieldAttributeAccess(Field field) {
this.name = field.getName();
try {
ReflectHelper.ensureAccessibility( field );
}
catch (Exception e) {
this.field = null;
return;
}
this.field = field;
}
public MethodAttributeAccess(String attributeName, Method method) {
this.name = attributeName;
try {
ReflectHelper.ensureAccessibility( method );
}
catch (Exception e) {
this.method = null;
return;
}
this.method = method;
}
public HibernateProxy deserializeProxy(SerializableProxy serializableProxy) {
final ByteBuddyInterceptor interceptor = new ByteBuddyInterceptor(
serializableProxy.getEntityName(),
serializableProxy.getPersistentClass(),
serializableProxy.getInterfaces(),
serializableProxy.getId(),
resolveIdGetterMethod( serializableProxy ),
resolveIdSetterMethod( serializableProxy ),
serializableProxy.getComponentIdType(),
null,
ReflectHelper.overridesEquals( serializableProxy.getPersistentClass() )
);
// note: interface is assumed to already contain HibernateProxy.class
try {
final Class proxyClass = buildProxy(
serializableProxy.getPersistentClass(),
serializableProxy.getInterfaces()
);
final HibernateProxy proxy = (HibernateProxy) proxyClass.newInstance();
( (ProxyConfiguration) proxy ).$$_hibernate_set_interceptor( interceptor );
return proxy;
}
catch (Throwable t) {
final String message = LOG.bytecodeEnhancementFailed( serializableProxy.getEntityName() );
LOG.error( message, t );
throw new HibernateException( message, t );
}
}
@Override
public Object intercept(Object proxy, Method thisMethod, Object[] args) throws Throwable {
Object result = this.invoke( thisMethod, args, proxy );
if ( result == INVOKE_IMPLEMENTATION ) {
Object target = getImplementation();
final Object returnValue;
try {
if ( ReflectHelper.isPublic( persistentClass, thisMethod ) ) {
if ( !thisMethod.getDeclaringClass().isInstance( target ) ) {
throw new ClassCastException(
target.getClass().getName()
+ " incompatible with "
+ thisMethod.getDeclaringClass().getName()
);
}
returnValue = thisMethod.invoke( target, args );
}
else {
thisMethod.setAccessible( true );
returnValue = thisMethod.invoke( target, args );
}
if ( returnValue == target ) {
if ( returnValue.getClass().isInstance( proxy ) ) {
return proxy;
}
else {
LOG.narrowingProxy( returnValue.getClass() );
}
}
return returnValue;
}
catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
else {
return result;
}
}
private static SQLExceptionConverter constructConverter(String converterClassName, ViolatedConstraintNameExtracter violatedConstraintNameExtracter) {
try {
LOG.tracev( "Attempting to construct instance of specified SQLExceptionConverter [{0}]", converterClassName );
final Class converterClass = ReflectHelper.classForName( converterClassName );
// First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param...
final Constructor[] ctors = converterClass.getDeclaredConstructors();
for ( Constructor ctor : ctors ) {
if ( ctor.getParameterTypes() != null && ctor.getParameterCount() == 1 ) {
if ( ViolatedConstraintNameExtracter.class.isAssignableFrom( ctor.getParameterTypes()[0] ) ) {
try {
return (SQLExceptionConverter) ctor.newInstance( violatedConstraintNameExtracter );
}
catch (Throwable ignore) {
// eat it and try next
}
}
}
}
// Otherwise, try to use the no-arg constructor
return (SQLExceptionConverter) converterClass.newInstance();
}
catch (Throwable t) {
LOG.unableToConstructSqlExceptionConverter( t );
}
return null;
}