When generate Qclasses, they look like,
@Generated("com.querydsl.codegen.DefaultEntitySerializer")
public class QWhatever extends EntityPathBase<Whatever> {
// ...
public static final QWhatever whatever = new QWhatever("whatever");
// ...
}
Is there any utility class/method for fetching the whatever
field's value?
I wrote a utility class, and it works, yet I feel re-invented the wheel.
@SuppressWarnings({"unchecked"})
public static <T extends EntityPathBase<?>> T getInstance(final Class<T> entityPathBaseClass) {
Objects.requireNonNull(entityPathBaseClass, "entityPathBaseClass is null");
return (T) INSTANCESputeIfAbsent(
entityPathBaseClass,
k -> Arrays.stream(entityPathBaseClass.getDeclaredFields())
.filter(f -> {
final var modifiers = f.getModifiers();
if (!Modifier.isPublic(modifiers)) {
return false;
}
if (!Modifier.isStatic(modifiers)) {
return false;
}
if (!Modifier.isFinal(modifiers)) {
return false;
}
if (f.getType() != entityPathBaseClass) {
return false;
}
return true;
})
.findFirst()
.map(f -> {
if (!f.canAccess(null)) {
f.setAccessible(true);
}
return f;
})
.map(f -> {
try {
return f.get(null);
} catch (final IllegalAccessException iae) {
throw new RuntimeException("failed to get value of " + f, iae);
}
})
.orElseThrow(() -> new IllegalArgumentException(
"unable to find the instance field from " +
entityPathBaseClass
))
);
}