querydsl - How can I get the value of the instance field form a QClass? - Stack Overflow

When generate Qclasses, they look like,@Generated("com.querydsl.codegen.DefaultEntitySerializer&q

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
                        ))
        );
    }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744660796a4586450.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信