Skip to content

Instantly share code, notes, and snippets.

@bmchild
Created April 9, 2012 13:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmchild/2343316 to your computer and use it in GitHub Desktop.
Save bmchild/2343316 to your computer and use it in GitHub Desktop.
Get Entity Class from spring JpaRepository
@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