Created
April 9, 2012 13:15
-
-
Save bmchild/2343316 to your computer and use it in GitHub Desktop.
Get Entity Class from spring JpaRepository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SuppressWarnings("rawtypes") | |
public static Class<?> getEntity(JpaRepository repo) { | |
Type clazzes = getGenericType(repo.getClass())[0]; | |
Type[] jpaClass = getGenericType(getClass(clazzes)); | |
return getClass( ((ParameterizedType)jpaClass[0]).getActualTypeArguments()[0]); | |
} | |
public static Type[] getGenericType(Class<?> target) { | |
if (target == null) | |
return new Type[0]; | |
Type[] types = target.getGenericInterfaces(); | |
if (types.length > 0) { | |
return types; | |
} | |
Type type = target.getGenericSuperclass(); | |
if (type != null) { | |
if (type instanceof ParameterizedType) { | |
return new Type[] { type }; | |
} | |
} | |
return new Type[0]; | |
} | |
/* | |
* Get the underlying class for a type, or null if the type is a variable | |
* type. | |
* | |
* @param type | |
* @return the underlying class | |
*/ | |
@SuppressWarnings("rawtypes") | |
private static Class<?> getClass(Type type) { | |
if (type instanceof Class) { | |
return (Class) type; | |
} else if (type instanceof ParameterizedType) { | |
return getClass(((ParameterizedType) type).getRawType()); | |
} else if (type instanceof GenericArrayType) { | |
Type componentType = ((GenericArrayType) type).getGenericComponentType(); | |
Class<?> componentClass = getClass(componentType); | |
if (componentClass != null) { | |
return Array.newInstance(componentClass, 0).getClass(); | |
} else { | |
return null; | |
} | |
} else { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment