Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
  * JBoss, Home of Professional Open Source
  * Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 package org.hibernate.validator.internal.util;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
 import static org.hibernate.validator.internal.util.CollectionHelper.newHashMap;
 import static org.hibernate.validator.internal.util.logging.Messages.MESSAGES;

Some reflection utility methods. Where necessary calls will be performed as PrivilegedAction which is necessary for situations where a security manager is in place.

Author(s):
Hardy Ferentschik
Gunnar Morling
Kevin Pollet <kevin.pollet@serli.com> (C) 2011 SERLI
 
 public final class ReflectionHelper {
 
 	private static final Log log = LoggerFactory.make();
 
 	private static String[] PROPERTY_ACCESSOR_PREFIXES = { "is""get""has" };
 
 	private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPES;
 
 	static {
 		Map<Class<?>, Class<?>> temp = newHashMap( 9 );
 
 		temp.putboolean.classBoolean.class );
 		temp.putchar.classCharacter.class );
 		temp.putdouble.classDouble.class );
 		temp.putfloat.classFloat.class );
 		temp.putlong.classLong.class );
 		temp.putint.classInteger.class );
 		temp.putshort.classShort.class );
 		temp.putbyte.classByte.class );
 		temp.put.. );
 
 		 = Collections.unmodifiableMaptemp );
 	}

Private constructor in order to avoid instantiation.
 
 	private ReflectionHelper() {
 	}
 
 	public static ClassLoader getClassLoaderFromContext() {
		ClassLoader loader;
		GetClassLoader action = GetClassLoader.fromContext();
		if ( System.getSecurityManager() != null ) {
			loader = AccessController.doPrivilegedaction );
		}
		else {
			loader = action.run();
		}
		return loader;
	}
	public static ClassLoader getClassLoaderFromClass(Class<?> clazz) {
		ClassLoader loader;
		GetClassLoader action = GetClassLoader.fromClassclazz );
		if ( System.getSecurityManager() != null ) {
			loader = AccessController.doPrivilegedaction );
		}
		else {
			loader = action.run();
		}
		return loader;
	}
	public static Class<?> loadClass(String classNameClass<?> caller) {
		LoadClass action = LoadClass.actionclassNamecaller );
		if ( System.getSecurityManager() != null ) {
			return AccessController.doPrivilegedaction );
		}
		else {
			return action.run();
		}
	}
	public static <T> Constructor<T> getConstructor(Class<T> clazzClass<?>... params) {
		Constructor<T> constructor;
		GetConstructor<T> action = GetConstructor.actionclazzparams );
		if ( System.getSecurityManager() != null ) {
			constructor = AccessController.doPrivilegedaction );
		}
		else {
			constructor = action.run();
		}
		return constructor;
	}
	public static <T> T newInstance(Class<T> clazzString message) {
instance;
		NewInstance<T> newInstance = NewInstance.actionclazzmessage );
		if ( System.getSecurityManager() != null ) {
			instance = AccessController.doPrivilegednewInstance );
		}
		else {
			instance = newInstance.run();
		}
		return instance;
	}
	public static <T> T newConstructorInstance(Constructor<T> constructorObject... initArgs) {
instance;
		ConstructorInstance<T> newInstance = ConstructorInstance.actionconstructorinitArgs );
		if ( System.getSecurityManager() != null ) {
			instance = AccessController.doPrivilegednewInstance );
		}
		else {
			instance = newInstance.run();
		}
		return instance;
	}
	public static <T> T getAnnotationParameter(Annotation annotationString parameterNameClass<T> type) {
result;
		GetAnnotationParameter<T> action = GetAnnotationParameter.actionannotationparameterNametype );
		if ( System.getSecurityManager() != null ) {
			result = AccessController.doPrivilegedaction );
		}
		else {
			result = action.run();
		}
		return result;
	}

Process bean properties getter by applying the JavaBean naming conventions.

Parameters:
member the member for which to get the property name.
Returns:
The bean method name with the "is" or "get" prefix stripped off, null the method name id not according to the JavaBeans standard.
	public static String getPropertyName(Member member) {
		String name = null;
		if ( member instanceof Field ) {
			name = member.getName();
		}
		if ( member instanceof Method ) {
			String methodName = member.getName();
			for ( String prefix :  ) {
				if ( methodName.startsWithprefix ) ) {
					name = Introspector.decapitalizemethodName.substringprefix.length() ) );
				}
			}
		}
		return name;
	}

Checks whether the given method is a valid JavaBeans getter method, meaning its name starts with "is" or "has" and it has no parameters.

Parameters:
method The method of interest.
Returns:
true, if the given method is a JavaBeans getter method, false otherwise.
	public static boolean isGetterMethod(Method method) {
		return getPropertyNamemethod ) != null && method.getParameterTypes().length == 0;
	}

Checks whether the property with the specified name and type exists on the given class.

Parameters:
clazz The class to check for the property. Cannot be null.
property The property name without 'is', 'get' or 'has'. Cannot be null or empty.
elementType The element type. Either ElementType.FIELD or ElementType METHOD.
Returns:
true is the property and can be access via the specified type, false otherwise.
	public static boolean propertyExists(Class<?> clazzString propertyElementType elementType) {
		return getMemberclazzpropertyelementType ) != null;
	}

Returns the member with the given name and type.

Parameters:
clazz The class from which to retrieve the member. Cannot be null.
property The property name without 'is', 'get' or 'has'. Cannot be null or empty.
elementType The element type. Either ElementType.FIELD or ElementType METHOD.
Returns:
the member which matching the name and type or null if no such member exists.
	public static Member getMember(Class<?> clazzString propertyElementType elementType) {
		Contracts.assertNotNullclazz.classCannotBeNull() );
		if ( property == null || property.length() == 0 ) {
		}
		if ( !( ..equalselementType ) || ..equalselementType ) ) ) {
		}
		Member member = null;
		if ( ..equalselementType ) ) {
			GetDeclaredField action = GetDeclaredField.actionclazzproperty );
			if ( System.getSecurityManager() != null ) {
				member = AccessController.doPrivilegedaction );
			}
			else {
				member = action.run();
			}
		}
		else {
			String methodName = property.substring( 0, 1 ).toUpperCase() + property.substring( 1 );
			for ( String prefix :  ) {
				GetMethod action = GetMethod.actionclazzprefix + methodName );
				if ( System.getSecurityManager() != null ) {
					member = AccessController.doPrivilegedaction );
				}
				else {
					member = action.run();
				}
				if ( member != null ) {
					break;
				}
			}
		}
		return member;
	}

Returns the type of the field of return type of a method.

Parameters:
member the member for which to get the type.
Returns:
Returns the type of the field of return type of a method.
	public static Class<?> getType(Member member) {
		Class<?> type = null;
		if ( member instanceof Field ) {
			type = ( (Fieldmember ).getType();
		}
		if ( member instanceof Method ) {
			type = ( (Methodmember ).getReturnType();
		}
		return type;
	}

Parameters:
member The Member instance for which to retrieve the type.
Returns:
Returns the Type of the given Field or Method.
Throws:
java.lang.IllegalArgumentException in case member is not a Field or Method.
	public static Type typeOf(Member member) {
		Type type;
		if ( member instanceof Field ) {
			type = ( (Fieldmember ).getGenericType();
		}
		else if ( member instanceof Method ) {
			type = ( (Methodmember ).getGenericReturnType();
		}
		else {
		}
		if ( type instanceof TypeVariable ) {
			type = TypeHelper.getErasedTypetype );
		}
		return type;
	}

Returns the type of the parameter of the given method with the given parameter index.

Parameters:
method The method of interest.
parameterIndex The index of the parameter for which the type should be returned.
Returns:
The erased type.
	public static Type typeOf(Method methodint parameterIndex) {
		Type type = method.getGenericParameterTypes()[parameterIndex];
		if ( type instanceof TypeVariable ) {
			type = TypeHelper.getErasedTypetype );
		}
		return type;
	}
	public static Object getValue(Member memberObject object) {
		Object value = null;
		if ( member instanceof Method ) {
			Method method = (Methodmember;
			try {
				value = method.invokeobject );
			}
			catch ( IllegalAccessException e ) {
			}
			catch ( InvocationTargetException e ) {
			}
		}
		else if ( member instanceof Field ) {
			Field field = (Fieldmember;
			try {
				value = field.getobject );
			}
			catch ( IllegalAccessException e ) {
			}
		}
		return value;
	}
	public static void setAccessibility(Member member) {
		SetAccessibility action = SetAccessibility.actionmember );
		if ( System.getSecurityManager() != null ) {
			AccessController.doPrivilegedaction );
		}
		else {
			action.run();
		}
	}

Determines the type of elements of an Iterable, array or the value of a Map.

Parameters:
type the type to inspect
Returns:
Returns the type of elements of an Iterable, array or the value of a Map. null is returned in case the type is not indexable (in the context of JSR 303).
	public static Type getIndexedType(Type type) {
		Type indexedType = null;
		if ( isIterabletype ) && type instanceof ParameterizedType ) {
			ParameterizedType paramType = (ParameterizedTypetype;
			indexedType = paramType.getActualTypeArguments()[0];
		}
		else if ( isMaptype ) && type instanceof ParameterizedType ) {
			ParameterizedType paramType = (ParameterizedTypetype;
			indexedType = paramType.getActualTypeArguments()[1];
		}
		else if ( TypeHelper.isArraytype ) ) {
			indexedType = TypeHelper.getComponentTypetype );
		}
		return indexedType;
	}

Parameters:
type the type to check.
Returns:
Returns true if type is a iterable type, false otherwise.
	public static boolean isIterable(Type type) {
		if ( type instanceof Class && Iterable.class.isAssignableFrom( (Class<?>) type ) ) {
			return true;
		}
		if ( type instanceof ParameterizedType ) {
			return isIterable( ( (ParameterizedTypetype ).getRawType() );
		}
		if ( type instanceof WildcardType ) {
			Type[] upperBounds = ( (WildcardTypetype ).getUpperBounds();
			return upperBounds.length != 0 && isIterableupperBounds[0] );
		}
		return false;
	}

Parameters:
type the type to check.
Returns:
Returns true if type is implementing Map, false otherwise.
	public static boolean isMap(Type type) {
		if ( type instanceof Class && Map.class.isAssignableFrom( (Class<?>) type ) ) {
			return true;
		}
		if ( type instanceof ParameterizedType ) {
			return isMap( ( (ParameterizedTypetype ).getRawType() );
		}
		if ( type instanceof WildcardType ) {
			Type[] upperBounds = ( (WildcardTypetype ).getUpperBounds();
			return upperBounds.length != 0 && isMapupperBounds[0] );
		}
		return false;
	}

Parameters:
type the type to check.
Returns:
Returns true if type is implementing List, false otherwise.
	public static boolean isList(Type type) {
		if ( type instanceof Class && List.class.isAssignableFrom( (Class<?>) type ) ) {
			return true;
		}
		if ( type instanceof ParameterizedType ) {
			return isList( ( (ParameterizedTypetype ).getRawType() );
		}
		if ( type instanceof WildcardType ) {
			Type[] upperBounds = ( (WildcardTypetype ).getUpperBounds();
			return upperBounds.length != 0 && isListupperBounds[0] );
		}
		return false;
	}

Tries to retrieve the indexed value from the specified object.

Parameters:
value The object from which to retrieve the indexed value. The object has to be non null</null> and either a collection or array.
index The index. The index does not have to be numerical. value could also be a map in which case the index could also be a string key.
Returns:
The indexed value or null if value is null or not a collection or array. null is also returned in case the index does not exist.
	public static Object getIndexedValue(Object valueInteger index) {
		if ( value == null ) {
			return null;
		}
		Iterator<?> iter;
		Type type = value.getClass();
		if ( isIterabletype ) ) {
			iter = ( (Iterable<?>) value ).iterator();
		}
		else if ( TypeHelper.isArraytype ) ) {
			List<?> arrayList = Arrays.asList( (Objectvalue );
			iter = arrayList.iterator();
		}
		else {
			return null;
		}
		int i = 0;
		while ( iter.hasNext() ) {
			o = iter.next();
			if ( i == index ) {
				return o;
			}
			i++;
		}
		return null;
	}

Tries to retrieve the mapped value from the specified object.

Parameters:
value The object from which to retrieve the mapped value. The object has to be non null and must implement the @{code Map} interface.
key The map key. index.
Returns:
The mapped value or null if value is null or not implementing @{code Map}.
	public static Object getMappedValue(Object valueObject key) {
		if ( !( value instanceof Map ) ) {
			return null;
		}
		Map<?, ?> map = (Map<?, ?>) value;
		//noinspection SuspiciousMethodCalls
		return map.getkey );
	}

Returns the declared field with the specified name or null if it does not exist.

Parameters:
clazz The class to check.
fieldName The field name.
Returns:
Returns the declared field with the specified name or null if it does not exist.
	public static Field getDeclaredField(Class<?> clazzString fieldName) {
		GetDeclaredField action = GetDeclaredField.actionclazzfieldName );
		final Field field;
		if ( System.getSecurityManager() != null ) {
			field = AccessController.doPrivilegedaction );
		}
		else {
			field = action.run();
		}
		return field;
	}

Checks whether the specified class contains a declared field with the given name.

Parameters:
clazz The class to check.
fieldName The field name.
Returns:
Returns true if the field exists, false otherwise.
	public static boolean containsDeclaredField(Class<?> clazzString fieldName) {
		return getDeclaredFieldclazzfieldName ) != null;
	}

Returns the fields of the specified class.

Parameters:
clazz The class for which to retrieve the fields.
Returns:
Returns the fields for this class.
	public static Field[] getDeclaredFields(Class<?> clazz) {
		GetDeclaredFields action = GetDeclaredFields.actionclazz );
		final Field[] fields;
		if ( System.getSecurityManager() != null ) {
			fields = AccessController.doPrivilegedaction );
		}
		else {
			fields = action.run();
		}
		return fields;
	}

Returns the method with the specified property name or null if it does not exist. This method will prepend 'is' and 'get' to the property name and capitalize the first letter.

Parameters:
clazz The class to check.
methodName The property name.
Returns:
Returns the method with the specified property or null if it does not exist.
	public static Method getMethodFromPropertyName(Class<?> clazzString methodName) {
		Method method;
		GetMethodFromPropertyName action = GetMethodFromPropertyName.actionclazzmethodName );
		if ( System.getSecurityManager() != null ) {
			method = AccessController.doPrivilegedaction );
		}
		else {
			method = action.run();
		}
		return method;
	}

Checks whether the specified class contains a method for the specified property.

Parameters:
clazz The class to check.
property The property name.
Returns:
Returns true if the method exists, false otherwise.
	public static boolean containsMethodWithPropertyName(Class<?> clazzString property) {
		return getMethodFromPropertyNameclazzproperty ) != null;
	}

Returns the method with the specified name or null if it does not exist.

Parameters:
clazz The class to check.
methodName The method name.
Returns:
Returns the method with the specified property or null if it does not exist.
	public static Method getMethod(Class<?> clazzString methodName) {
		Method method;
		GetMethod action = GetMethod.actionclazzmethodName );
		if ( System.getSecurityManager() != null ) {
			method = AccessController.doPrivilegedaction );
		}
		else {
			method = action.run();
		}
		return method;
	}

Returns the declared method with the specified name and parameter types or null if it does not exist.

Parameters:
clazz The class to check.
methodName The method name.
parameterTypes The method parameter types.
Returns:
Returns the declared method with the specified name or null if it does not exist.
	public static Method getDeclaredMethod(Class<?> clazzString methodNameClass<?>... parameterTypes) {
		Method method;
		GetDeclaredMethod action = GetDeclaredMethod.actionclazzmethodNameparameterTypes );
		if ( System.getSecurityManager() != null ) {
			method = AccessController.doPrivilegedaction );
		}
		else {
			method = action.run();
		}
		return method;
	}

Returns the declared methods of the specified class.

Parameters:
clazz The class for which to retrieve the methods.
Returns:
Returns the declared methods for this class.
	public static Method[] getDeclaredMethods(Class<?> clazz) {
		GetDeclaredMethods action = GetDeclaredMethods.actionclazz );
		final Method[] methods;
		if ( System.getSecurityManager() != null ) {
			methods = AccessController.doPrivilegedaction );
		}
		else {
			methods = action.run();
		}
		return methods;
	}

Returns the methods of the specified class (include inherited methods).

Parameters:
clazz The class for which to retrieve the methods.
Returns:
Returns the methods for this class.
	public static Method[] getMethods(Class<?> clazz) {
		GetMethods action = GetMethods.actionclazz );
		final Method[] methods;
		if ( System.getSecurityManager() != null ) {
			methods = AccessController.doPrivilegedaction );
		}
		else {
			methods = action.run();
		}
		return methods;
	}

Checks, whether the given methods have the same signature, which is the case if they have the same name, parameter count and types.

Parameters:
method1 A first method.
method2 A second method.
Returns:
True, if the methods have the same signature, false otherwise.
	public static boolean haveSameSignature(Method method1Method method2) {
		Contracts.assertValueNotNullmethod1"method1" );
		Contracts.assertValueNotNullmethod2"method2" );
		return
				method1.getName().equalsmethod2.getName() ) &&
						Arrays.equalsmethod1.getGenericParameterTypes(), method2.getGenericParameterTypes() );
	}

Returns the auto-boxed type of a primitive type.

Parameters:
primitiveType the primitive type
Returns:
the auto-boxed type of a primitive type. In case java.lang.Void is passed (which is considered as primitive type by java.lang.Class.isPrimitive()), java.lang.Void will be returned.
Throws:
java.lang.IllegalArgumentException in case the parameter primitiveType does not represent a primitive type.
	public static Class<?> boxedType(Class<?> primitiveType) {
		Class<?> wrapperType = .getprimitiveType );
		if ( wrapperType == null ) {
			throw .getHasToBeAPrimitiveTypeExceptionprimitiveType.getClass() );
		}
		return wrapperType;
	}

Get all superclasses and optionally interfaces recursively.

Parameters:
clazz The class to start the search with.
includeInterfaces whether or not to include interfaces
Returns:
List of all super classes and interfaces of clazz. The list contains the class itself! The empty list is returned if clazz is null.
	public static List<Class<?>> computeClassHierarchy(Class<?> clazzboolean includeInterfaces) {
		List<Class<?>> classes = new ArrayList<Class<?>>();
		computeClassHierarchyclazzclassesincludeInterfaces );
		return classes;
	}

Get all superclasses and interfaces recursively.

Parameters:
clazz The class to start the search with
classes List of classes to which to add all found super classes and interfaces
includeInterfaces whether or not to include interfaces
	private static void computeClassHierarchy(Class<?> clazzList<Class<?>> classesboolean includeInterfaces) {
		for ( Class<?> current = clazzcurrent != nullcurrent = current.getSuperclass() ) {
			if ( classes.containscurrent ) ) {
				return;
			}
			classes.addcurrent );
			if ( includeInterfaces ) {
				for ( Class<?> currentInterface : current.getInterfaces() ) {
					computeClassHierarchycurrentInterfaceclassesincludeInterfaces );
				}
			}
		}
	}

Get all interfaces a class directly implements.

Parameters:
clazz The class for which to find the interfaces
Returns:
Set of all interfaces clazz implements. The empty list is returned if clazz does not implement any interfaces or clazz is null
	public static Set<Class<?>> computeAllImplementedInterfaces(Class<?> clazz) {
		Set<Class<?>> classes = new HashSet<Class<?>>();
		computeAllImplementedInterfacesclazzclasses );
		return classes;
	}
	private static void computeAllImplementedInterfaces(Class<?> clazzSet<Class<?>> classes) {
		if ( clazz == null ) {
			return;
		}
		for ( Class<?> currentInterface : clazz.getInterfaces() ) {
			classes.addcurrentInterface );
			computeAllImplementedInterfacescurrentInterfaceclasses );
		}
	}
New to GrepCode? Check out our FAQ X