Skip to content

Commit

Permalink
Merge pull request #134 from tbouvet/feat-5-typeOf
Browse files Browse the repository at this point in the history
Add a raw type for TypeOf
  • Loading branch information
tbouvet committed Oct 8, 2015
2 parents 0a49ce2 + b7a21ac commit bf1df9d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
31 changes: 24 additions & 7 deletions specs/src/main/java/org/seedstack/seed/core/api/TypeOf.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
import java.lang.reflect.Type;

/**
* Capture a generic type and resolve it. For example:
* Capture a generic type and resolve it. For example:
*
* <pre>
* <code>
* new TypeOf&lt;Repository&lt;AggregateRoot&lt;Long&gt;,Long&gt;&gt;() {}
Expand All @@ -22,26 +23,42 @@
*
* @author thierry.bouvet@mpsa.com
*
* @param <T> Parameterized type to capture.
* @param <T>
* Parameterized type to capture.
*/
public abstract class TypeOf<T> {

private final Type type;
private final Class<? super T> rawType;

protected TypeOf() {
Type superclass = getClass().getGenericSuperclass();
if ( ! (superclass instanceof ParameterizedType) ) {
throw new SeedException(CoreErrorCode.MISSING_GENERIC_PARAMETER);
}
this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
Type superclass = getClass().getGenericSuperclass();
if (!(superclass instanceof ParameterizedType)) {
throw new SeedException(CoreErrorCode.MISSING_GENERIC_PARAMETER);
}
this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
Class<?> clazz = type instanceof Class<?> ? (Class<?>)type : (Class<?>) ((ParameterizedType) type).getRawType();
@SuppressWarnings("unchecked")
Class<? super T> clazz2 = (Class<? super T>) clazz;
this.rawType = clazz2;

}

/**
* Returns the raw type with the generic types from this reference.
*
* @return parameterized type
*/
public Type getType() {
return this.type;
}

/**
* Returns the raw type from this reference.
* @return the rawType
*/
public Class<? super T> getRawType() {
return rawType;
}

}
10 changes: 8 additions & 2 deletions specs/src/test/java/org/seedstack/seed/core/api/TypeOfTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,17 @@ public class TypeOfTest {
* Test method for {@link org.seedstack.seed.core.api.TypeOf#getType()}.
*/
@Test
public void testGetType() {
public void testResult() {
TypeOf<List<String>> typeOf = new TypeOf<List<String>>() {
};
Assertions.assertThat(typeOf.getType().toString()).isEqualTo("java.util.List<java.lang.String>");

Assertions.assertThat(typeOf.getRawType()).isEqualTo(List.class);

TypeOf<Long> typeOf2 = new TypeOf<Long>() {
};
Assertions.assertThat(typeOf2.getType()).isEqualTo(Long.class);
Assertions.assertThat(typeOf2.getRawType()).isEqualTo(Long.class);

}

/**
Expand Down

0 comments on commit bf1df9d

Please sign in to comment.