Generic field type issue (inheritance)
Thanks to #439, there is base generic type support for fields. But there are cases still not covered: e.g. if the generic type is inherited. The given test shows an issue:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class GenericComplicatedTest {
@Test
void genericInheritedShouldBeCorrectlyPopulated() {
// given
EasyRandom easyRandom = new EasyRandom();
// when
SubLongResource longResource = easyRandom.nextObject(SubLongResource.class);
// note: with this call instead the test is success
// InterLongResource longResource = easyRandom.nextObject(InterLongResource.class);
// then
assertThat(longResource.getId())
.isInstanceOf(Long.class);
}
private static abstract class IdResource<K, T extends IdResource<K, ?>> {
private K id;
@SuppressWarnings("unchecked")
public T setId(K id) {
this.id = id;
return (T) this;
}
public K getId() {
return id;
}
}
private static class InterLongResource<T extends InterLongResource<T>> extends IdResource<Long, T> {
}
private static class SubLongResource extends InterLongResource<SubLongResource> {
}
}
Fails with message:
java.lang.ClassCastException: class org.jeasy.random.GenericComplicatedTest$SubLongResource cannot be cast to class java.lang.Long (org.jeasy.random.GenericComplicatedTest$SubLongResource is in unnamed module of loader 'app'; java.lang.Long is in module java.base of loader 'bootstrap')
at org.jeasy.random.GenericComplicatedTest.genericInheritedShouldBeCorrectlyPopulated(GenericComplicatedTest.java:42)
Thank you for reporting this. Indeed, ER seems to resolve K as SubLongResource instead of Long. As mentioned in https://github.com/j-easy/easy-random/issues/425#issuecomment-723494900 , I'm not expecting ER to support this kind of use cases out of the box, that's why I updated the known limitations section accordingly when I released 4.3:
Due to type erasure, there are some cases where Easy Random is not able to get the information required
about a class or a field type at runtime.
Your use case is clearly one of them. That said, I will try to see if we can improve things in the next iteration (at least try to correctly detect unsupported cases and throw an exception with a clear message about that).